Can't quick sort become stable sort?

こ雲淡風輕ζ 提交于 2019-12-31 02:44:11

问题


Approach 1

C.A.R Hoare introduced partitioning logic(shown below), which is taught in school,

low = pivot = 0;
i = 1;
j = high = listSize-1;

while (true) {
    while (a[i] <= a[pivot] && (i < high)) {
        i = i + 1;
    }
    while (a[j] >= a[pivot] && (j > low)) {
        j = j - 1; 
    }

    if (i >= j)
        break;
    swap(a[i], a[j])
}

swap(a[j], a[pivot]); // pivot element is positioned(once)
return j;

Approach 2

To basically try make it stable sort, Instead j pointing to last index(listSize-1), if j points to listSize/2(i.e., mid), then,

we get into scenario where j > high or i >= mid, where a[i] do not have corresponding a[j] to swap with and vice-versa. In such scenario, swapping a[i] with a[pivot] also does not make sense, which looks an incorrect approach, To confirm the same,


My question:

With approach 2,

By maintaining the essence of quick sort, Can't we partition with pivot element(at any index)?

Note: Analyzing quick sort, not a home work


回答1:


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.



来源:https://stackoverflow.com/questions/41715443/cant-quick-sort-become-stable-sort

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