sort.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. int in[] = {10, 32, -1, 567, 3, 18, 1, -51, 789, 0};
  2. main() {
  3. int i;
  4. sort(in, (sizeof in)/(sizeof in[0]));
  5. for (i = 0; i < (sizeof in)/(sizeof in[0]); i++) {
  6. putd(in[i]);
  7. putchar('\n');
  8. }
  9. return 0;
  10. }
  11. /* putd - output decimal number */
  12. putd(n) {
  13. if (n < 0) {
  14. putchar('-');
  15. n = -n;
  16. }
  17. if (n/10)
  18. putd(n/10);
  19. putchar(n%10 + '0');
  20. }
  21. int *xx;
  22. /* sort - sort a[0..n-1] into increasing order */
  23. sort(a, n) int a[]; {
  24. quick(xx = a, 0, --n);
  25. }
  26. /* quick - quicksort a[lb..ub] */
  27. quick(a, lb, ub) int a[]; {
  28. int k, partition();
  29. if (lb >= ub)
  30. return;
  31. k = partition(a, lb, ub);
  32. quick(a, lb, k - 1);
  33. quick(a, k + 1, ub);
  34. }
  35. /* partition - partition a[i..j] */
  36. int partition(a, i, j) int a[]; {
  37. int v, k;
  38. j++;
  39. k = i;
  40. v = a[k];
  41. while (i < j) {
  42. i++; while (a[i] < v) i++;
  43. j--; while (a[j] > v) j--;
  44. if (i < j) exchange(&a[i], &a[j]);
  45. }
  46. exchange(&a[k], &a[j]);
  47. return j;
  48. }
  49. /* exchange - exchange *x and *y */
  50. exchange(x, y) int *x, *y; {
  51. int t;
  52. printf("exchange(%d,%d)\n", x - xx, y - xx);
  53. t = *x; *x = *y; *y = t;
  54. }