exc/k&r/04-funcs-and-prog-struct/04-qsort.c

44 lines
1.0 KiB
C

#include <stdio.h>
#include <stdlib.h>
void qsort_book(int v[], int left, int right);
/* sorts command line arguments */
int main(int argc, char *argv[])
{
int i, v[argc-1];
for (i = 1; i < argc; i++)
v[i-1] = atoi(argv[i]);
qsort_book(v, 0, argc-2);
for (i = 0; i < argc-1; i++)
printf("%d ", v[i]);
putchar('\n');
return 0;
}
/* swap: swap v[i] and v[j] */
void swap(int *v, int i, int j)
{
int temp = v[i];
v[i] = v[j], v[j] = temp;
}
/* qsort: sort v[left]...v[right] into increasing order */
void qsort_book(int v[], int left, int right)
{
int i, last;
if (left >= right) /* do nothing if array contains */
return; /* fewer than two elements */
swap(v, left, (left + right)/2); /* move partition elem */
last = left; /* to v[0] */
for (i = left+1; i <= right; i++) /* partition */
if (v[i] < v[left])
swap(v, ++last, i);
swap(v, left, last); /* restore partition elem */
qsort_book(v, left, last-1);
qsort_book(v, last+1, right);
}