If you want to rotate an circular array then there could be two approaches. For this code sample we are taking following resources :
a[] – an integer array
n= Number of integers in array a[]
k= Times we want to rotate array. (Every time one is added to the index of element)
First approach : –
1 2 3 4 5 6 7 8 9 10 |
void rotate (int a[], int n, int k){ int temp; for(int m=0;m<k;m++){ temp=a[n-1]; for(int i=n-1;i>0;i--){ a[i]=a[i-1]; } a[0]=temp; } } |
Second approach :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
int * rotate (int a[], int n, int k){ int temp; int *c = malloc(sizeof(int)*n); for(int i=0;i<n;i++){ if((i+k)>(n-1)){ c[(i+k)-n]=a[i]; } else{ c[k+i]=a[i]; } } return c; } |
Now you can clearly see the difference. Second approach is faster and i think fastest for rotating the array because we are only iterating n times whereas in first approach we are iterating n*k times. If you know better way then comment below.