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;
}
}
}