given an array of integers in random order you have to find the minimum number of swaps to convert it to cyclic sorted array

前端 未结 4 651
野趣味
野趣味 2021-02-06 04:16

if an array is given in random order , you have to output the minimum number of swaps required to convert into cyclic sorted array.

e.g. array given is 3 5 4 2 1

4条回答
  •  故里飘歌
    2021-02-06 04:40

    Assuming:

    1. The array elements are the integers 1 to N.

    Steps:

    1. Allocate a second (histogram) array H of length N.
    2. In a single pass through the initial array A, for each index i increment H[ (A[i] - i) % N]
    3. In a single pass through H, identify the element R of H with the maximum count
    4. Clear H.
    5. Identify the number of Orbits in the original array under a rotation by R. (by stepping forward through H until H[i]=0, then stepping through the orbit for which A[i] is a member under the rotation R) setting H[i]=1 for each member of the orbit, and repeating until the element H[N-1] has been processed (counting the nubmer of orbits as you go). This is also O(N) as each element of A is visited exactly once.
    6. The required number of swaps = N - Orbits.

    This is O(N).

    Update: I have updated the algorithm to account for multiple orbits. In processing each orbit, the final swap places two elements instead of just 1.

    I suspect that the number of Orbits is invariant under any rotation, which would simplify the algorithm considerbly but would not affect it's complexity, which remains at O(N).

提交回复
热议问题