Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quick sort, Hoare partitioning, using random pivot

Other than below, is there a better way to do quick sort using random pivot(I could not do without a swap)? Please advise

int hoare_par (int *a, int b, int e)
{
    if (b < e) {
        int p_i = __random(b, e);
        __swap(&a[b], &a[p_i])

        int p = a[b];
        b = b - 1;
        e = e + 1;

        while (1) {
            do { ++b;} while (a[b] < p);
            do { --e;} while (a[e] > p);
            if (b < e)
                 __swap( &a[b], &a[e]);
            else
                 return e;
        }
    }
    return e;
}

Also, please let me know if incorrect. Thanks!

like image 270
codey modey Avatar asked Mar 08 '26 05:03

codey modey


1 Answers

If you take a peek at Wikipedia's article and study the pseudocode for Hoare partitioning given there, you'll see that all the partitioning scheme cares about is that the selected pivot is somewhere in the range (it serves as a sentinel to avoid running out of the range for both indices). So you can just pick any element of the range at random as pivot element and do the partitioning as written down there.

like image 93
vonbrand Avatar answered Mar 10 '26 15:03

vonbrand



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!