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
[3 4 5 2 3 1 4]
[1 4 3 4 5 2 3
def shift(nelements, k): result = [] length = len(nelements) start = (length - k) % length for i in range(length): result.append(nelements[(start + i) % length]) return result
This code works well even on negative shift k