Rotating an array in place

 

April 13, 2010 in Uncategorized

Rotate a one-dimensional array of n elements to the right by k steps. 
For instance, with n=7 and k=3, the array {a, b, c, d, e, f, g} is rotated to {e, f, g, a, b, c, d}.

 

In my previous post we discussed about finding an element in a rotated array. You might ask, how do we rotate an array?

The straight forward way is to allocate a temporary array of size n, and then copy elements starting from index k to the new array, and copy it back to the old array. This is highly inefficient because:

    1. It needs extra space to store a temporary array (O(n) space).

 

    1. It involves back-and-forth copying, a total of 2*n copy operations.

 

So, the question is, can we do this more efficiently, preferably an in-place rotation method.

The answer is of course, yes. This is a trick so important that it becomes one of the frequently asked interview questions. An in-depth discussion is in Programming Pearls, one of the must-read book in Computer Science.

The trick is to do three reverse operation. One for the entire string, one from index 0 to k-1, and lastly index k to n-1. Magically, this will yield the correct rotated array, without any extra space! (Of course, you need a temporary variable for swapping).

 

 

posted on 2014-10-09 05:53  brave_bo  阅读(181)  评论(0编辑  收藏  举报

导航