Tuesday, January 3, 2012

Rotate an Array

Write a function rotate(ar[], d, n) that rotates arr[] of size n by d elements.

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:

It needs extra space to store a temporary array (O(n) space).
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.

http://www.programcreek.com/2015/03/rotate-array-in-java/

3 Methods: Temp Array, Rotate one by one, Rotate a set:
http://www.geeksforgeeks.org/array-rotation/

Block Swap Algorithm:
http://www.geeksforgeeks.org/block-swap-algorithm-for-array-rotation/

Reversal algorithm for array rotation:
http://articles.leetcode.com/rotating-array-in-place
http://www.geeksforgeeks.org/program-for-array-rotation-continued-reversal-algorithm/

1 comment:

  1. Merge Sorted arrays inplace:
    http://mycareerstack.com/question/30/

    ReplyDelete