Fastest algorithm for circle shift N sized array for M position

If you want O(n) time and no extra memory usage (since array was specified), use the algorithm from Jon Bentley’s book, “Programming Pearls 2nd Edition”. It swaps all the elements twice. Not as fast as using linked lists but uses less memory and is conceptually simple.

shiftArray( theArray, M ):
    size = len( theArray )
    assert( size > M )
    reverseArray( theArray, 0, size - 1 )
    reverseArray( theArray, 0, M - 1 )
    reverseArray( theArray, M, size - 1 )

reverseArray( anArray, startIndex, endIndex ) reverses the order of elements from startIndex to endIndex, inclusive.

Leave a Comment