1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include <stdio.h>
void print_list(int *ar, int n) { int i; printf("[ "); for (i=0; i<n; i++) { printf("%d ", ar[i]); } printf("]\n");
}
int partition(int *ar, int left, int right) { int x, i, j; int tmp;
x = ar[right]; i = left; for (j=left; j<right; j++) { if (ar[j] <= x) { tmp = ar[j]; ar[j] = ar[i]; ar[i] = tmp; i++; } } tmp = ar[i]; ar[i] = ar[right]; ar[right] = tmp; return i; }
void quick_sort(int *ar, int left, int right) { int index; if (left < right) { index = partition(ar, left, right); quick_sort(ar, left, index-1); quick_sort(ar, index, right); } }
int main(int argc, char *argv[]) { int a[] = {15, 9, 8, 1, 4, 11, 7, 12, 13, 16, 5, 3, 16, 2, 10, 14}; int len=sizeof(a)/sizeof(int); printf("begin: "); print_list(a, len); quick_sort(a, 0, len-1); printf("end "); print_list(a, len); return 0; }
|