/* BEGIN new.c */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define SORT_FUNCTIONS \
no_sort, "Original order of the test arrays:", \
slsort, "Nonstable simple selection sort:", \
i_sort, "Stable insertionsort:", \
qsort, "Standard library qsort;\n" \
"unspecified ordering of equal keys:"
#define NUMBERS \
"zero","one","two","three","four","five", \
"six","seven","eight","nine","ten"
#define NMEMB(A) (sizeof (A) / sizeof *(A))
int comp(const void *a, const void *b);
void no_sort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
void slsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
void i_sort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
int
main(void)
{
size_t element, sort;
struct sf {
void (*func)(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *));
const char *description;
} s_F[] = {SORT_FUNCTIONS};
const char numbers[][sizeof "three"] = {NUMBERS};
char array[NMEMB(numbers)][sizeof "three"];
puts("\n/* BEGIN output from new.c */\n\n"
"Arrays of (char [sizeof \"three\"]),\n"
"are being sorted by string length.\n");
for (sort = 0; sort != NMEMB(s_F); ++sort) {
memcpy(array, numbers, sizeof array);
s_F[sort].func(array, NMEMB(array), sizeof*array, comp);
puts(s_F[sort].description);
for (element = 0; element != NMEMB(array); ++element) {
puts(array[element]);
}
putchar('\n');
}
puts("/* END output from new.c */");
return 0;
}
int
comp(const void *a, const void *b)
{
const char (*const aaa)[sizeof "three"] = a;
const char (*const bbb)[sizeof "three"] = b;
const char *aa = *aaa;
const char *bb = *bbb;
while (*aa != '\0' && *bb != '\0') {
++aa;
++bb;
}
return *bb != '\0' ? -1 : *aa != '\0';
}
void
no_sort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
base, nmemb, size, compar;
}
void
slsort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
size_t tail;
unsigned char *array, *first, *middle, *end, swap;
if (nmemb-- > 1) {
end = base;
do {
array = end;
end += size;
first = middle = end;
tail = nmemb;
while (--tail != 0) {
middle += size;
if (compar(first, middle) > 0) {
first = middle;
}
}
if (compar(array, first) > 0) {
do {
swap = *first;
*first++ = *array;
*array++ = swap;
} while (array != end);
}
} while (--nmemb != 0);
}
}
void
i_sort(void *base, size_t nmemb, size_t size,
int (*compar)(const void *, const void *))
{
unsigned char *array, *low, *high, *p1, *p2, swap;
if (nmemb-- > 1) {
array = base;
do {
low = array;
high = low + size;
array = high;
while (compar(low, high) > 0) {
p1 = high;
p2 = low;
do {
swap = *p1;
*p1++ = *p2;
*p2++ = swap;
} while (p2 != high);
if (low == base) {
break;
}
high = low;
low -= size;
}
} while (--nmemb != 0);
}
}
/* END new.c */
--
pete