Juggling Algorithm

前端 未结 2 1837
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 19:06

METHOD (A Juggling Algorithm) Divide the array in different sets where number of sets is equal to GCD of n and d and move the elements within sets. If GCD is 1 as is for the abo

2条回答
  •  执笔经年
    2021-01-27 19:42

    The for loop in the function:

    leftRotate(int arr[], int d, int n)
    

    is going to make exatcly gcd(d, n) iterations. Now lets look at what is happening inside the loop: it takes all the cells arr[k]which fulfill: k % gcd(d, n) == i and swaps them. Of course there are exactly: n / gcd(d, n) of them and that is how many swaps the function will make in one iteration of the loop. Therefore the whole asymptotic time complexity of the function is going to be O(gcd(d, n) * n / gcd(d, n)) == O(n). The rest of the code does not have an impact on the time complexity and is pretty much self explainatory.

提交回复
热议问题