数组旋转



所以我想写一个c++程序来执行数组旋转r次。现在,一次数组旋转意味着数组的第一个元素移动到最后一个位置,所有位于第(i)个位置的其他元素移动到第(i)个位置。

我所面临的问题是,即使我已经应用了一个forloop的次数旋转应该发生,但然后数组也只旋转一次。请帮助我,我错过了什么。

#include<iostream>
using namespace std;
int main()
{
int i,n,r,arr1[100],arr2[100];
cout<<"Please enter the number of elements in your array: "<<endl;
cin>>n;
cout<<"Please enter the number of rotations to be performed: "<<endl;
cin>>r;
for(i=0;i<n;i++)
{
cin>>arr1[i];
}    
for(i=0;i<r;i++)
{   
arr2[n-1]=arr1[0];
for(i=1;i<n;i++)
{
arr2[i-1]=arr1[i];
}
}
cout<<"Printing now:"<<endl;
for(i=0;i<n;i++)
{
cout<<arr2[i]<<"t";
}
}
void Rotate(int arr[], int n, int r){
/* To get the starting point of rotated array */
int mod = r % n;

// Prints the rotated array from start position
for (int i = 0; i < n; i++)
cout << (arr[(mod + i) % n]) << " ";

cout << "n";
}

试试这段代码。你可以在这里阅读更多信息

对于想要完整工作代码的人:

#include <bits/stdc++.h>
using namespace std;

void leftRotate(int arr[], int n, int k)
{
/* To get the starting point of rotated array */
int mod = k % n;
// Prints the rotated array from start position
for (int i = 0; i < n; i++)
cout << (arr[(mod + i) % n]) << " ";
cout << "n";
}
int main()
{
int n,k,arr[100];
cout<<"Please enter the number of elements: "<<endl;
cin>>n;
cout<<"Now enter the elements:"<<endl;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"Enter the number of rotations to be performed: "<<endl;
cin>>k;

leftRotate(arr, n, k);
return 0;
}
#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
ll n,r;
cin>>n>>r;
ll a[n];
/* pre-compute the index where the element would be present after rotation 
by 'r' times and then insert it in the array */
for(ll i=0; i<n; i++)
{
ll index = ((n+i)-r)%n;
cin>>a[index];
}
// print the rotated array
for(ll i=0; i<n; i++)
{
cout<<a[i]<<" ";
}
}

最新更新