In the recursion section of K&R's ANSI C book, they demonstrate a
version of quicksort [that] is not the fastest possible, but it's one of the simplest.
--The C Programming Language (ANSI C) - pg. 87
In its entirety:
/*qsort: sort v[left]...v[right] into increasing order*/
void qsort(int v[], int left, int right){
int i, last;
/*do nothing if array has less than 2 elements*/
if(left >= right)
return;
swap(v, left, (left + right) / 2);
last = left;
/*partition*/
for(i = left + 1; i <= right; i++)
if(v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last); /*reset partition element*/
qsort(v, left, last - 1);
qsort(v, last + 1, right);
}
where swap(v, i, j)
swaps two members of the array v
.
I'm trying to figure out how this sorts the array. It looks like last
is an array element that separates the array into two smaller arrays and then swapped with the left bounding element. It is then compared to all elements up to the right bound, swapping each smaller element with ++last
(why?).
Finally, the partition element is swapped back in and the two subarrays are sorted separately.
If I understand the recursion correctly, this algorithm means at the end of one pass all the elements to the left of last
are smaller than all the elements to the right of last
. I am having trouble finding an explanation because most qsort
algorithms are more complicated than this one.