4

I know there are several similar posts, but none of the answers are satisfying, which is why I want to ask this question again.

Consider the code below. It is my implementation of quick sort according to CRLS Introduction to Algorithms

int partition(int* a, int s, int e)
{
    int pivot = a[e];
    int q = s-1;
    for (int i = s; i <= e; i++)
    {
        if (a[i] <= pivot) {
            q++;
            int tmp = a[q];
            a[q] = a[i];
            a[i] = tmp;
        }
    }
    return q;
}

void quickSort(int* a, int s, int e)
{
    if (e > s) {
        int q = partition(a, s, e);
        quickSort(a, s, q-1);
        quickSort(a, q+1, e);
    }
}

Stable sorting algorithms maintain the relative order of records with equal keys (i.e., values). I don't understand why quick sort is not one of them. Although there are swaps between unadjacent elements in it, but I still don't see why that will cause unstability. I really hope someone could give examples to explain this.

Thank you.

eaglesky
  • 730
  • 2
  • 13
  • 28
  • 1
    See this answer http://stackoverflow.com/a/10375393/1196603 for a visual example – Jk1 Jan 14 '14 at 05:44
  • @Jk1:Thank you for your fast reply. That's the exact answer I want. It's a very good link. I wonder why the answer in the link is not chosen as the best answer. – eaglesky Jan 14 '14 at 05:50
  • Possible duplicate of [quicksort alogorithm stability](http://stackoverflow.com/questions/13498213/quicksort-alogorithm-stability) – Cody Gray - on strike Jun 02 '16 at 16:02

2 Answers2

2

In stable sorting algorithms,the swapping or spring occurs only with adjacent elements. For example in mergesort,the elements are made into units of one then, sorted accordingly using merge function .I think if u consider linear sort,its self explanatory. But that's not the case in quick sort.

0

try [ 1,1,1,5,5,5,5,1,1,1,4], pivot is 4 ,and when i meets the stronger "1",it swaps the first 5 with this "1"

luchy0120
  • 55
  • 1
  • 6
  • 1
    To elaborate on this example a bit, actually, [5(1st), 5(2nd), 5(3rd), 1, 4] should do, where 4 is the pivot, when we swap 1 with the first 5, we get [1, 5(2nd), 5(3rd), 5(1st), 4], swapping the second 5 with the pivot gives us [1, 4, 5(3rd), 5(1st), 5(2nd)], which is the final result we will get with quicksort, clearly, the original order of 5 is not preserved, i.e., not stable. It doesn't matter with integers, but it matters let's say you are sorting a list of points in the cartesian plane by the x coordinate, (5,1),(5,2),(5,3),(1,1),(4,1). – Ken H Mar 14 '20 at 21:58