Algorithm to rotate an array in linear time

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

    Let us say we have a function called arr_reverse(arr,i,j) which reverses the elements of the array arr between index i and j using the swap function.

    Example:

    arr = {1,2,3,4,5} 
    i = 0
    j = 2
    

    then the function will return:

    {3,2,1,4,5} 
     ^^^^^
    

    Implementing this function is straight forward and is O(N).

    Now let's use this function in rotating the array.

    arr     = {1,2,3,4,5} // input array
    k       = 2 // amount of right rotation
    result  = {4,5,1,2,3} // expected result 
    l       = 5 // length of array.
    
    Step 1: Call arr_reverse(arr,l-k,l-1) which is arr_reverse(arr,3,4)
    we get {1,2,3,5,4} 
                  ^^^
    
    Step 2: Call arr_reverse(arr,0,l-k-1) which is arr_reverse(arr,0,2)
    we get {3,2,1,5,4}
            ^^^^^     
    
    Step 3: Call arr_reverse(arr,0,l-1) which is arr_reverse(arr,0,4)
    we get {4,5,1,2,3} 
            ^^^^^^^^^
    

    The entire process makes use of arr_reverse 3 times, making it O(N)

提交回复
热议问题