I am not sure if I fully understood your question. But it looks like you really want to rotate the contents of the array.
To rotate the contents of the array left k times. You can do the following:
- Flip the first elements of K.
- Flip the rest of the NK items.
- Flip the entire array.
Example:
N = 5, K = 3 and array = [1 2 3 4 5]
- step 1: undo the first 3 elements: [3 2 1 4 5]
- Step 2: undo the remaining 2 items: [3 2 1 5 4]
- Step 3: discard the entire array: [4 5 1 2 3]
The C ++ function does the same:
void move (int a[100], int n, int k) { int t[100]; int i,j; for (i=k-1,j=0; i>=0; i--,j++) t[j]=a[i]; for (i=n-1; i>=k; i--,j++) t[j]=a[i]; for (i=n-1,j=0; i>=0; i--,j++) a[j]=t[i]; }
The best way to do this in a constant space is to make a U-turn in place:
void arr_rev(int a[100], int start, int end) { int temp; for(;start<end;start++,end
source share