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 591
野趣味
野趣味 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:47

    I think the approach here should be - sort all the numbers into a helper array. Then for each cyclic shift calculate the number of swaps needed to get the original array to this cyclic shift. Choose the minimal of those.

    To find minimal number of swaps required to get array A to array B simply count the number of interchanged values(i.e. value a is on the left of value b in A but vice versa in array B). This problem is equivelent to counting the inversions in a given array and can be solved using modified merge sort again in O(n*log(n)).

    The complexity of my approach is O(n^2*log(n))(because you do a merge sort for all cyclic shifts of an array of size n).

    I can not think of a faster solution for your problem.

提交回复
热议问题