2014-09-24 14:45:10 +00:00
|
|
|
/*
|
|
|
|
!!DESCRIPTION!! simple quicksort, tests recursion
|
|
|
|
!!ORIGIN!! LCC 4.1 Testsuite
|
|
|
|
!!LICENCE!! own, freely distributeable for non-profit. read CPYRIGHT.LCC
|
|
|
|
*/
|
|
|
|
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
|
|
|
|
int in[] = {10, 32, -1, 567, 3, 18, 1, -51, 789, 0};
|
|
|
|
int *xx;
|
|
|
|
|
|
|
|
/* exchange - exchange *x and *y */
|
|
|
|
exchange(int *x,int *y) {
|
|
|
|
int t;
|
|
|
|
|
2019-02-12 21:50:49 +00:00
|
|
|
printf("exchange(%d,%d)\n", x - xx, y - xx);
|
|
|
|
t = *x; *x = *y; *y = t;
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* partition - partition a[i..j] */
|
|
|
|
int partition(int a[], int i, int j) {
|
|
|
|
int v, k;
|
|
|
|
|
2019-02-12 21:50:49 +00:00
|
|
|
j++;
|
|
|
|
k = i;
|
|
|
|
v = a[k];
|
|
|
|
while (i < j) {
|
|
|
|
i++; while (a[i] < v) i++;
|
|
|
|
j--; while (a[j] > v) j--;
|
|
|
|
if (i < j) exchange(&a[i], &a[j]);
|
|
|
|
}
|
|
|
|
exchange(&a[k], &a[j]);
|
|
|
|
return j;
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* quick - quicksort a[lb..ub] */
|
|
|
|
void quick(int a[], int lb, int ub) {
|
|
|
|
int k;
|
|
|
|
|
2019-02-12 21:50:49 +00:00
|
|
|
if (lb >= ub)
|
|
|
|
return;
|
|
|
|
k = partition(a, lb, ub);
|
|
|
|
quick(a, lb, k - 1);
|
|
|
|
quick(a, k + 1, ub);
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* sort - sort a[0..n-1] into increasing order */
|
|
|
|
sort(int a[], int n) {
|
2019-02-12 21:50:49 +00:00
|
|
|
quick(xx = a, 0, --n);
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/* putd - output decimal number */
|
|
|
|
void putd(int n) {
|
2019-02-12 21:50:49 +00:00
|
|
|
if (n < 0) {
|
|
|
|
putchar('-');
|
|
|
|
n = -n;
|
|
|
|
}
|
|
|
|
if (n/10)
|
|
|
|
putd(n/10);
|
|
|
|
putchar(n%10 + '0');
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
int main(void) {
|
2019-02-12 21:50:49 +00:00
|
|
|
int i;
|
2014-09-24 14:45:10 +00:00
|
|
|
|
2019-02-12 21:50:49 +00:00
|
|
|
sort(in, (sizeof in)/(sizeof in[0]));
|
|
|
|
for (i = 0; i < (sizeof in)/(sizeof in[0]); i++) {
|
|
|
|
putd(in[i]);
|
|
|
|
putchar('\n');
|
|
|
|
}
|
2014-09-24 14:45:10 +00:00
|
|
|
|
2019-02-12 21:50:49 +00:00
|
|
|
return 0;
|
2014-09-24 14:45:10 +00:00
|
|
|
}
|
|
|
|
|