Can't quick sort become stable sort?

假如想象 提交于 2019-12-02 02:52:06

This looks like home work, so I am not going to solve it completely:

  • quick-sort can be made stable by ensuring that no 2 elements compare equal.

  • choosing a different pivot alone does not provide a solution for this.

Since you say this is not homework, here is how to make quick-sort stable:

  • make an array of pointers to the original array.
  • use quick-sort to sort this array with a function that compares the pointed values this way:

    int sortptr(const void *a, const void *b) {
        const my_type * const *pa = a;
        const my_type * const *pb = b;
        int cmp = original_compare_function(*pa, *pb);
        return cmp ? cmp : (pa > pb) - (pa < pb);
    }
    
  • copy the sorted items into a sorted array.

Note that this approach can be made to work in place, but it is tricky to do so and would still require allocating the array of pointers. merge-sort is much more reliable for stable sorting, but requires working space of approximately half the size of the original array.

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