Looking for portable sort
BRIAN OLENDER
brian.olender at canremote.uucp
Sat Sep 23 10:37:00 AEST 1989
Subj: Looking for portable sort algorithm
*-*-*-*-* Message continued from prior message *-*-*-*-*
void hsort(void *, size_t, size_t, comp_t);
void
hsort (void *base, /* pointer to the array base */
size_t nel, /* number of elements */
size_t width, /* size of elements */
comp_t comp) /* comparison function */
{
char *i, *j, *l, *ir, *temp;
if (nel < 2)
return; /* if not at least two elements *
if (!(temp = (char *)malloc(width)))
return; /* memory allocation error */
ir = (char *)base + (nel - 1) * width; /* last element */
l = (char *)base + (nel >> 1) * width; /* middle element + 1 */
for (;;) {
if (l <= base) { /* selection phase */
memcpy(temp, ir, width); /* make room here */
memcpy(ir, base, width); /* select top of heap */
ir -= width;
if (ir <= base) {
memcpy(base, temp, width); /* smallest element */
free(temp);
return;
}
}
else { /* heap creation phase */
l -= width;
memcpy(temp, l, width); /* element to be sifted */
}
/* sift down element in temp to its proper level */
j = l;
while (i = j, (j += (j - base + width)) <= ir) {
if (j < ir && (*comp)(j, j + width) < 0)
j += width;
if ((*comp)(j, temp) < 0)
break;
memcpy(i, j, width); /* demote element in temp */
}
memcpy(i, temp, width); /* this is temp's level */
}
}
======== cut here =========
__ ____
/ ) / / /) /
/--< __ o __. ____ / / (/ _ ____ __/ _ __
/___/ / (_<_ (_/|_/ / <_ /___/ _/\_(/_/ / <_(_/|_(/__/ (_
---
* Via ProDoor 3.1aR
More information about the Comp.lang.c
mailing list