Internal Implementation of Qsort

Anubhav Agarwal picture Anubhav Agarwal · Oct 17, 2013 · Viewed 13.9k times · Source

qsort is declared as

void qsort (void* base, size_t num, size_t size,
            int (*compar)(const void*,const void*));

I want to know how does qsort implements the reflection property. I mean how does it call the function whose name we passed ?

Answer

Filipe Gonçalves picture Filipe Gonçalves · Oct 17, 2013

qsort receives a pointer to function receiving two pointers and returning int, and that's just it. This pointer is called compar. All qsort needs to do to call this function is something like:

(*compar)(base+i, base+j);

Where i and j are offsets for base. It's really that simple. You can see a possible implementation in K&R second edition, section 5.11, page 120:

void qsort(void *v[], int left, int right, int (*comp)(void *, void *)) {
    int i, last;
    void swap(void *v[], int, int);

    if (left >= right)
        return;
    swap(v, left, (left + right)/2);
    last = left;
    for (i = left+1; i <= right; i++)
        if ((*comp)(v[i], v[left]) < 0) /* Here's the function call */
            swap(v, ++last, i);
    swap(v, left, last);
    qsort(v, left, last-1, comp);
    qsort(v, last+1, right, comp);
}