What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4]
shift M = 2 positions should be [1 4 3 4 5 2 3]
.
Thanks a lot.
What is the fastest algorithm for circle shifting array for M positions?
For example, [3 4 5 2 3 1 4]
shift M = 2 positions should be [1 4 3 4 5 2 3]
.
Thanks a lot.
Similar to @IsaacTurner and not that elegant due to unnecessary copying, but implementation is quite short.
The idea - swap element A on index 0 with the element B which sits on destination of A. Now B is first. Swap it with the element C which sits on destination of B. Continue until the destination is not at 0.
If the greatest common divisor is not 1 then you're not finished yet - you need to continue swapping, but now using index 1 at your starting and end point.
Continue until your starting position is not the gcd.
Swift 4 version for shifting array left.
For example, if input array is
a = [1, 2, 3, 4, 5]
, and left shift offset isd = 4
, then result will be[5, 1, 2, 3, 4]
circleArray
has some errors and is not working in all cases!The loop must continue
while i1 < i2
NOTi1 < last - 1
.Here is a simple and efficient general in place rotate function in C++, less than 10 lines.
which is excerpted from my answer on another question. How to rotate an array?
Ruby example:
Keep two indexes to the array, one index starts from beginning of the array to the end of array. Another index starts from the Mth position from last and loops through the last M elements any number of times. Takes O(n) at all times. No extra space required.