Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why quick sort is unstable

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.

like image 679
eaglesky Avatar asked May 09 '26 22:05

eaglesky


1 Answers

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.

like image 80
user5033407 Avatar answered May 11 '26 13:05

user5033407



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!