I find it difficult to understand the following snippet of code. I understand the pointer to function mannerism showed, but where I find confusion is in the indicated lines.
void qsort(void **v, int left, int right, int (*comp) (void *, void *))
{
int i, last;
void swap(int **v, int i, int j);
if (left >= right) /* do nothing if array contains */
return; /* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */ [1]
last = left; /* to v[0] */ [2]
for (i = left + 1; i <= right; i++) /* partition */ [3]
if ((*comp) (v[i], v[left]) < 0) [4]
swap(v, ++last, i); [5]
swap(v, left, last); /* restore partition elem */ [6]
qsort(v, left, last - 1); [7]
qsort(v, last + 1, right); [8]
}
Can someone explain this routine to me, especially the indicated lines, just tell me what it's doing, because I can't figure this qsort out, the eskimo guide I read whilst reading k&r said that the qsort routine is rubbish, and overly complicated. I just need to understand why it's written like this, because it makes no sense to me.
Thanks, if for nothing, for reading this.
magic useful google keywords: QuickSort
e.g. google:how quicksort works turns up this explanation: http://www.angelfire.com/pq/jamesbarbetti/articles/sorting/001a_HowQuicksortWorks.htm among others.
Essentially, the code applies a variation of quicksort to the elements between the
leftandrightboundaries specified.For the lines you've identified:
swap the middle element with the first (
left) one. it will become the "pivot".keep track of the boundary between bigger and smaller elements. this is where the pivot belongs.
move it before the first bigger element.
move the pivot back into place.
recursively apply qsort to the elements before the pivot. (the smaller ones)
recursively apply qsort to the elements after the pivot. (the bigger ones)
Try applying the code yourself to a list of numbers, and see if it makes more sense then....