kyle york said:
If, in the comparison routine, one was to compare the pointers if the
other data compare equal that would make it stable, yes?
At least that's my reading of 6.5.8.5
You can't compare the pointers passed to you by qsort() because the way it
works is to randomly select one item as a "pivot", move it to the lowest
place, and then run through the array putting all the items above the pivot
to the top and below the pivot to the bottom. The pivot is always the top of
the "bottom" heap. The pivot is now in the right place and you have two
unsorted arrays above and below it. So it then calls itself recursively on
those two arrays until the array length goes to one.
Here's a version I wrote. bubblesort() and swap() do what you would expect.
I can't see an easy way to undo the swapping of data items to make the sort
stable, without gobbling lots of extra memory.
/*
quicksort - quicksort algorithm
Params: ptr - base of array
N - number of items
sz - width of each item
comp - comparision function
*/
void quicksort(void *ptr, int N, int sz, int (*comp)(const void *e1, const
void *e2))
{
int pivot = 0;
int left = 1;
int right = N;
unsigned char *xptr = ptr;
if(N < 8)
{
bubblesort(ptr, N, sz, comp);
return;
}
else
{
swap(xptr, xptr + (N/2) * sz, sz);
while(left < right)
{
if ( (*comp)(xptr + left * sz, xptr + pivot * sz) <= 0)
{
left++;
}
else
{
right--;
swap(xptr + left * sz, xptr + right * sz, sz);
}
}
left--;
swap(xptr, xptr + left * sz, sz);
quicksort(xptr, left, sz, comp);
quicksort(xptr + (left + 1) * sz, N - left - 1, sz, comp);
}
}