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
| #include <time.h> #include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std;
#define N 10000
int InsertSort(int L[], int n) { for (int i = 0; i < n - 1; i++) for (int j = i; j >= 0; j--) if (L[j] > L[j + 1]) swap(L[j], L[j + 1]); return 0; } int QuickSort(int L[], int s, int t) { if (s >= t) return 0;
int temp = L[s]; int low = s, high = t; while (low < high) { while (low < high && L[high] >= temp) high--; L[low] = L[high];
while (low < high && L[low] <= temp) low++; L[high] = L[low]; } L[low] = temp; QuickSort(L, s, low - 1); QuickSort(L, low + 1, t); return 0; }
int AdjustHeap(int L[], int s, int n) { int i = s; int j = i + i + 1; while (j <= n) { if (j + 1 <= n && L[j + 1] > L[j]) j++; if (L[i] > L[j]) break; swap(L[i], L[j]); i = j; j = i + i + 1; } return 0; } int HeapSort(int L[], int n) { for (int i = n / 2 - 1; i >= 0; i--) AdjustHeap(L, i, n - 1);
for (int i = n - 1; i > 0; i--) { swap(L[0], L[i]); AdjustHeap(L, 0, i - 1); } return 0; }
void Print(int L[], int n) { for (int i = 0; i < N; i++) printf("%d ", L[i]); } int isOk(int L[], int n) { for (int i = 0; i < n - 1; i++) if (L[i + 1] < L[i]) return 0; return 1; }
int main() { srand((unsigned int)time(NULL)); int L1[N], L2[N], L3[N]; for (int i = 0; i < N; i++) { L1[i] = rand(); L2[i] = L1[i]; L3[i] = L1[i]; }
printf("插入排序Insert Sort:\n"); clock_t c1 = clock(); InsertSort(L1, N); clock_t c2 = clock(); cout << "Insert sort time = " << c2 - c1 << " ms." << endl; if (!isOk(L1, N)) cout << "Insert sort error!" << endl;
printf("快速排序Quick Sort:\n"); c1 = clock(); QuickSort(L2, 0, N - 1); c2 = clock(); cout << "Quick sort time = " << c2 - c1 << " ms." << endl; if (!isOk(L2, N)) cout << "Quick sort error!" << endl;
printf("堆排序Heap Sort:\n"); c1 = clock(); HeapSort(L3, N); c2 = clock(); cout << "Heap sort time = " << c2 - c1 << " ms." << endl; if (!isOk(L3, N)) cout << "Heap sort error!" << endl;
return 0; }
|