where number of sets is equal to GCD of n and d and move the elements within sets.
If GCD is 1 as is for the above example array (n = 7 and d =2), then elements will be moved within one set only, we just start with temp = arr[0] and keep moving arr[I+d] to arr[I] and finally store temp at the right place.Here is an example for n =12 and d = 3. GCD is 3 and
Let arr[] be {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}a) Elements are first moved in first set – (See below diagram for this movement) arr[] after this step --> {4 2 3 7 5 6 10 8 9 1 11 12}b) Then in second set. arr[] after this step --> {4 5 3 7 8 6 10 11 9 1 2 12}c) Finally in third set. arr[] after this step --> {4 5 6 7 8 9 10 11 12 1 2 3}
#include#include int gcd(int a,int b){ if(b==0) return a; else return gcd(b, a%b);}void leftRo(int *array, int step, int len){ int i, j, k, tmp; for (i = 0; i < gcd(step, len); i++) { tmp = array[i]; j = i; while (1) { k = j + step; if (k >= len) { k -= len; } if (k == i) break; array[j] = array[k]; j = k; } array[j] = tmp; }}void printArr(int *arr, int len) { int i; for (i = 0; i < len; i++) { printf("%d ", arr[i]); } printf("\n");}int main(int argc, char *argv[]){ int arr[12] = {1,2,3,4,5,6,7,8,9,10,11,12}; leftRo(arr, 3, 12); printArr(arr, 12); return 0;}