Quicksort - conditions that makes it stable

后端 未结 3 676
花落未央
花落未央 2021-02-15 23:21

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-16 00:03

    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.

提交回复
热议问题