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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #define N 100 void merge(int l, int r); void quick_sort(int q[], int l, int r); void down(int u); void swap(int* a, int* b); void ShellSort(int* arr, int n); int q[N],temp[N]; int a[N]; int h[N], cnt; int m[N]; int main(void) {
int b = 3,n; while (b--) { printf("请输入整数个数\n"); scanf("%d", &n); printf("请输入%d个整数\n", n); for (int i = 0; i < n; i++) { scanf("%d", &q[i]); a[i] = q[i]; h[i+1] = q[i]; m[i] = q[i]; } cnt=n; merge(0, n - 1); printf("归并排序的结果为:"); for (int i = 0; i < n; i++) printf("%d ", q[i]); quick_sort(a, 0, n - 1); printf("\n快速排序的结果为:"); for (int i = 0; i < n; i++) printf("%d ", a[i]); for (int i = n / 2; i; i--) down(i); printf("\n堆排序的结果为:"); for (int i = 1; i <=n; i++) { printf("%d ", h[1]); h[1] = h[cnt--]; down(1); } ShellSort(m, n); printf("\n希尔排序的结果为:"); for (int i = 0; i < n; i++) printf("%d ", m[i]); printf("\n"); }
return 0; } void merge(int l, int r) { if (l >= r) return; int mid = l + r >> 1; int k = 0, i = l, j = mid + 1;
merge(l, mid); merge(mid + 1, r); while (i <= mid && j <= r) { if (q[i] <= q[j]) temp[k++] = q[i++]; else temp[k++] = q[j++]; } while (i <= mid) temp[k++] = q[i++]; while (j <= r) temp[k++] = q[j++]; for (i = l, j = 0; i <= r; i++, j++) { q[i] = temp[j]; } } void quick_sort(int a[], int l, int r) { if (l >= r) return;
int i = l - 1, j = r + 1, x = a[l + r >> 1]; while (i < j) { do i++; while (a[i] < x); do j--; while (a[j] > x); if (i < j) swap(&a[i], &a[j]); }
quick_sort(a, l, j); quick_sort(a, j + 1, r); } void down(int u) { int t = u; if (u * 2 <= cnt && h[u * 2] < h[t]) t = u * 2; if (u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1; if (u != t) { swap(&h[u], &h[t]); down(t); } } void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
void ShellSort(int* arr, int n) { int gap = n; while (gap > 1) { gap = gap / 2; for (int i = 0; i < n - gap; ++i) { int end = i; int tem = arr[end + gap]; while (end >= 0) { if (tem < arr[end]) { arr[end + gap] = arr[end]; end -= gap; } else { break; } } arr[end + gap] = tem; } } }
|