/***
Rotate the array about an index k.
So if the input was 0 1 2 3 4 5 6
rotating the array about index = 2the o/p would be
3 4 5 6 0 1 2
***/
First, reverse the order of the elements in the whole list:
{xn, xn-1, ..., x1}
Then reverse the sublist containing the last k-1 elements, and then also the sublist containing the other n-k+1 elements:
{xk, xk+1, ..., xn, x1, ..., xk-1}
To illustrate rotating a list of n=5 elements so that k=4 is first:
1 2 3 4 5
reverse list:
5 4 3 2 1
break into sublists and reverse:
5 4 3 2 1
4 5 1 2 3
Each reversal is clearly O(n) and the swapping requires some small constant amount of storage.
1 comment:
Nice dispatch and this mail helped me alot in my college assignement. Gratefulness you on your information.
Post a Comment