可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This might be trivial, but I don't understand why the default implementation of Selection Sort is not stable?
At each iteration you find the minimum element in the remaining array. When finding this minimum, you can choose the first minimum you find, and only update it when an element is actually smaller than it. So, the chosen element at each iteration is the first minimum - meaning, it's first on the previous sort order. So, to my understanding, the current sort will not destroy an order generated by a previous sort on equal elements.
What am I missing?
回答1:
A small example:
Let b = B in
< B > , < b > , < a > , < C > (with a < b < c)
After one cycle the sequence is sorted but the order of B and b has changed:
< a > , < b > , < B > , < c >
But you can however implement Selections Sort stable if you, instead of switching, insert the minimum value. But for that to be efficient you should have a data structure that supports insertion at a low cost or otherwise you end up with quadratic complexity.
回答2:
The problem is that selection sort swaps elements from the front of the array into the spot vacated by the minimum element, which can mess up the sorted order. For example, suppose I'm sorting
(4, 0), (4, 1), (1, 0)
Selection sort first swaps the (1, 0) to the front:
(1, 0), (4, 1), (4, 0)
And now the (4, 0) and (4, 1) are out of order from where they started in the sort. Running this to completion leaves the elements in this order, and the 4s are out of order.
Hope this helps!
回答3:
Stable means does not calculate further if elements is already sorted, but it calculate till end hence it is not stable.