I thought I had a good understanding of how quicksort works, until I watched the vid on http://code.google.com/edu/algorithms/index.html where Jon Bentley introduced his "beautiful quicksort code", which is as follows:
void quicksort(int l, int u){
int i, m;
if(l >= u) return;
m = l;
for(i = l+1; i<= u; i++)
if(x[i] < x[l])
swap(++m, i); //this is where I'm lost. Why the heck does it preincrement?
swap(l, m);
quicksort(l, m-1);
quicksort(m+1, u);
}
Another part of the algo that confuses me is the final swap after the FOR loop. Why is that neccessary? Lets assume that the array is already in order. If that is true, no swaps will occur since x[i] > x[l]. At the end, we swap l with m. That screws up the order.
Am I missing something?
Thanks.