Algorithm to rotate an array in linear time

后端 未结 22 2135
我寻月下人不归
我寻月下人不归 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:05

    Using linear time O(2N+m), and constant space O(4). m = GCD(n, p)

    It's up to 50% faster than the swapping approach, because swapping requires writing O(N) times to a temporary.

    http://www.eis.mdx.ac.uk/staffpages/r_bornat/oldteaching/I2A/slides%209%20circshift.pdf

    for (m=0, count=0; count!=n; m++) {
        type t=A[m];
        for (i=m, j=m+p; j!=m; i=j, j = j+p

提交回复
热议问题