Algorithm to rotate an array in linear time

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

    /* Q: How can we shift/rotate an array in place?
    A: "in place" means O(1) space complexity, so we need to do some trick
     */
    
    #include 
    #include 
    using namespace std;
    
    void ArrayRotate(int a[], int n, int k)
    {
        if (n < 1 || k % n == 0 ) return;
    
        k %= n;
        if (k < 0) k += n;
    
        reverse(a, a+k);
        reverse(a+k, a+n);
        reverse(a, a+n);
    }
    
    void PrintArray(int a[], int n)
    {
        for ( int i = 0 ; i < n; ++i)
            cout << a[i] << " ";
        cout << endl;
    }
    
    int main()
    {
        int a[] = { 1, 2 , 3, 4, 5 };
        int n = sizeof(a)/sizeof (a[0]);
    
        PrintArray(a, n);
        ArrayRotate(a, n, 2);
        PrintArray(a, n);
    
        return 0;
    }
    /* Output:
    1 2 3 4 5
    3 4 5 1 2
     */
    

提交回复
热议问题