Main Page | Class Hierarchy | Alphabetical List | Data Structures | Directories | File List | Data Fields | Globals

sort.c

Go to the documentation of this file.
00001 int in[] = {10, 32, -1, 567, 3, 18, 1, -51, 789, 0};
00002 
00003 main() {
00004     int i;
00005 
00006     sort(in, (sizeof in)/(sizeof in[0]));
00007     for (i = 0; i < (sizeof in)/(sizeof in[0]); i++) {
00008         putd(in[i]);
00009         putchar('\n');
00010     }
00011     return 0;
00012 }
00013 
00014 /* putd - output decimal number */
00015 putd(n) {
00016     if (n < 0) {
00017         putchar('-');
00018         n = -n;
00019     }
00020     if (n/10)
00021         putd(n/10);
00022     putchar(n%10 + '0');
00023 }
00024 
00025 int *xx;
00026 
00027 /* sort - sort a[0..n-1] into increasing order */
00028 sort(a, n) int a[]; {
00029     quick(xx = a, 0, --n);
00030 }
00031 
00032 /* quick - quicksort a[lb..ub] */
00033 quick(a, lb, ub) int a[]; {
00034     int k, partition();
00035 
00036     if (lb >= ub)
00037         return;
00038     k = partition(a, lb, ub);
00039     quick(a, lb, k - 1);
00040     quick(a, k + 1, ub);
00041 }
00042 
00043 /* partition - partition a[i..j] */
00044 int partition(a, i, j) int a[]; {
00045     int v, k;
00046 
00047     j++;
00048     k = i;
00049     v = a[k];
00050     while (i < j) {
00051         i++; while (a[i] < v) i++;
00052         j--; while (a[j] > v) j--;
00053         if (i < j) exchange(&a[i], &a[j]);
00054     }
00055     exchange(&a[k], &a[j]);
00056     return j;
00057 }
00058 
00059 /* exchange - exchange *x and *y */
00060 exchange(x, y) int *x, *y; {
00061     int t;
00062 
00063     printf("exchange(%d,%d)\n", x - xx, y - xx);
00064     t = *x; *x = *y; *y = t;
00065 }

Generated on Thu Aug 25 12:38:17 2005 for Quake III Arena by  doxygen 1.3.9.1