Algorithm to rotate an array in linear time

后端 未结 22 2134
我寻月下人不归
我寻月下人不归 2020-11-28 05:05

How to rotate an integer array by i times using swap function only in linear time.

22条回答
  •  醉酒成梦
    2020-11-28 06:03

    Here's a better solution, of a different nature than the others. It involves fewer array swaps than the others. Python:

    import fractions
    # rotates an array in-place i positions to the left, in linear time
    def rotate(arr,i):
        n = len(arr)
        reps = fractions.gcd(n,i)
        swaps = n / reps
        for start in xrange(reps):
            ix = start
            tmp = arr[ix]
            for s in xrange(swaps-1):
                previx = ix
                ix = (ix + i) % n
                arr[previx] = arr[ix]
            arr[ix] = tmp
        return arr
    

提交回复
热议问题