How can I implement a stable quicksort algorithm using O(n) additional space?

巧了我就是萌 提交于 2020-01-06 04:27:06

问题


I am allowed to use an extra array to perform a stable quicksort unlike the general quicksort algorithm. I know how to select the pivot at random and partition accordingly but I'm not able to figure out how to make use of the additional array to make it stable.


回答1:


The most trivial way that comes to mind is to store the initial indices in the array (1, 2, 3, etc) and swap them around as you swap the data.

Then in the comparison, if the two elements are equal, compare their indices too, thus making it stable.




回答2:


As suggested by Blindy and R, you can sort just the indices, then a variation of cycle sort can be used to sort the original array in place, with the side effect the that the sorted indices will be rearranged back to 0 to n-1. Every move places an element in place, so the time complexity is O(n).

void reorder_according_to(int array[], size_t indices[], size_t len)  
{
size_t i, j, k;
int t;
    for(i = 0; i < len; i++){
        if(i != indices[i]){
            t = array[i];
            k = i;
            while(i != (j = indices[k])){
                array[k] = array[j];
                indices[k] = k;
                k = j;
            }
            array[k] = t;
            indices[k] = k;
        }
    }
}


来源:https://stackoverflow.com/questions/32675087/how-can-i-implement-a-stable-quicksort-algorithm-using-on-additional-space

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