Find Minimum Number of Swaps to Sort an Array [duplicate]

元气小坏坏 提交于 2019-11-28 06:04:10

问题


This question already has an answer here:

  • Compute the minimal number of swaps to order a sequence 13 answers

Given an array with distinct elements, what is the minimum number of swap needed to sort it?

For example, the array [4, 2, 1, 3] needs at least 2 swaps (e.g. swapping 4 and 1 then 4 and 3).

This is my approach:

B = sort(copy(A))
for i = 0 ... len(A) - 1
    if A[i] != B[i]
        find j such that A[j] == B[i]
        swap(A[i], A[j])

Is my approach corrert? Is there another way to solve it?


回答1:


That depends on whether you're trying to find the minimum number of swaps, or actually trying to sort the array.

If you're trying to sort the array, the minimum number of swaps will not help you sort it faster. Finding the best sorting algorithm will help you sort faster. Generally, that means finding one with an O(n log(n)) complexity (unless the array is small or memory is a major constraint). For help with this problem, Google is your friend.

If you're just trying to find the minimum number of swaps needed, without actually sorting it, you're looking at some modification of the selection sort. The way that one goes is find the lowest value, swap with the first index, find the second-lowest, swap with the second index, etc.

But as I said, finding the minimum amount of swaps does not optimize sorting. The selection sort may have fewer swaps than the quicksort, for example, but it takes longer for the selection sort to determine which indeces to swap. The time complexity of the selection sort is O(n^2).

The difference between O(n^2) and O(n log(n)) is not as trivial as it looks, by the way. If the number is around 1,000,000, it could be the difference between 20,000,000 and 1,000,000,000,000.



来源:https://stackoverflow.com/questions/38980407/find-minimum-number-of-swaps-to-sort-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!