Given an array of n elements, write an algorithm to rotate it right by k element without using any other array. In other words rotate an array in place.
So the trick is to reverse the whole array first then reverse the array from 0 to k-1 and k to n-1.
http://www.geeksforgeeks.org/array-rotation/
Read full article from Rotate an array right by k element without using any other array
Rotation of the above array by 2 will make array
void rotateRight(int[] a, int k){ int length = a.length();//in C/C++ it will be given as input reverse(a, 0, length -1);//reverse whole array reverse(a, 0, k-1);//assuming 0 < k < length reverse(1, k, n-1); } void reverse(int[] a, int start, int end){ while(start < end){ swap(a, start, end); start++; end--; } }Also refer to http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/
http://www.geeksforgeeks.org/array-rotation/
Read full article from Rotate an array right by k element without using any other array
No comments:
Post a Comment