Quicksort - conditions that makes it stable

后端 未结 3 626
你的背包
你的背包 2021-02-15 23:45

A sorting algorithm is stable if it preserves the relative order of any two elements with equals keys. Under which conditions is quicksort stable?

Quick

相关标签:
3条回答
  • 2021-02-15 23:52

    The condition is easy to figure out, just keep the raw order for equal elements. There is no other condition that has essential differences from this one. The point is how to achieve it.

    There is a good example.

    1. Use the middle element as the pivot.

    2. Create two lists, one for smaller, the other for larger.

    3. Iterate from the first to the last and put elements into the two lists. Append the element smaller than or equals to and ahead of the pivot to the smaller list, the element larger than or equals to and behind of the pivot to the larger list. Go ahead and recursive the smaller list and the larger list.

    https://www.geeksforgeeks.org/stable-quicksort/

    The latter 2 points are both necessary. The middle element as the pivot is optional. If you choose the last element as pivot, just append all equal elements to the smaller list one by one from the beginning and they will keep the raw order in nature.

    0 讨论(0)
  • 2021-02-15 23:59

    Well, it is quite easy to make a stable quicksort that uses O(N) space rather than the O(log N) that an in-place, unstable implementation uses. Of course, a quicksort that uses O(N) space doesn't have to be stable, but it can be made to be so.

    I've read that it is possible to make an in-place quicksort that uses O(log N) memory, but it ends up being significantly slower (and the details of the implementation are kind of beastly).

    Of course, you can always just go through the array being sorted and add an extra key that is its place in the original array. Then the quicksort will be stable and you just go through and remove the extra key at the end.

    0 讨论(0)
  • 2021-02-16 00:06

    You can add these to a list, if that's your approach:

    • When the elements have absolute ordering
    • When the implementation takes O(N) time to note the relative orderings and restores them after the sort
    • When the pivot chosen is ensured to be of a unique key, or the first occurence in the current sublist.
    0 讨论(0)
提交回复
热议问题