Algorithm to rotate an array in linear time

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

    void reverse_array(int a[], int start, int end){
    
        while(start < end){     
                int temp =  a[start];
                a[start] = a[end];
                a[end] = temp;
                start++;
                end--;
        }
    

    }

    void rotate_array(int a[], int pivot, int len){
        int i;
        /*Reverse the whole array */
        reverse_array(a, 0, len);
    
        /* Reverse from 0 to pivot and pivot to end */
        reverse_array(a,0, pivot);
        reverse_array(a,pivot+1,len);
    

    }

提交回复
热议问题