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 : –
void rotate (int a[], int n, int k){ int temp; for(int m=0;m0;i--){ a[i]=a[i-1]; } a[0]=temp; } }
Second approach :
int * rotate (int a[], int n, int k){ int temp; int *c = malloc(sizeof(int)*n); for(int i=0;i(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.