Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stability of quicksort partitioning approach

Tags:

Does the following Quicksort partitioning algorithm result in a stable sort (i.e. does it maintain the relative position of elements with equal values):

  partition(A,p,r)   {      x=A[r];      i=p-1;      for j=p to r-1        if(A[j]<=x)           i++;           exchange(A[i],A[j])         exchang(A[i+1],A[r]);       return i+1;    } 
like image 550
mawia Avatar asked Aug 14 '09 14:08

mawia


People also ask

What is partitioning in Quicksort?

The key process in quickSort is a partition(). The target of partitions is, given an array and an element x of an array as the pivot, put x at its correct position in a sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x.

Is naive Quicksort stable?

Is naive quicksort stable? Yes, naive quicksort is stable because the partitioning algorithm is stable since it maintains the relative ordering of equal items.

Is Quicksort stable and adaptive?

The Quicksort Algorithm is Not Adaptive, Can we make QuickSort Algorithm Adaptive? Yes, we can make it Adaptive very easily.


1 Answers

There is one case in which your partitioning algorithm will make a swap that will change the order of equal values. Here's an image that helps demonstrate how your in-place partitioning algorithm works:

Partition Algorithm

We march through each value with the j index, and if the value we see is less than the partition value, we append it to the light-gray subarray by swapping it with the element that is immediately to the right of the light-gray subarray. The light-gray subarray contains all the elements that are <= the partition value. Now let's look at, say, stage (c) and consider the case in which three 9's are in the beginning of the white zone, followed by a 1. That is, we are about to check whether the 9's are <= the partition value. We look at the first 9 and see that it is not <= 4, so we leave it in place, and march j forward. We look at the next 9 and see that it is not <= 4, so we also leave it in place, and march j forward. We also leave the third 9 in place. Now we look at the 1 and see that it is less than the partition, so we swap it with the first 9. Then to finish the algorithm, we swap the partition value with the value at i+1, which is the second 9. Now we have completed the partition algorithm, and the 9 that was originally third is now first.

like image 199
Rose Perrone Avatar answered Oct 30 '22 15:10

Rose Perrone