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
| #include <cstdio> #include <cstdlib> #include <ctime> using namespace std;
template <typename T> void swap(T& a, T& b) { T c = a; a = b; b = c; }
template <typename T> inline bool comp(T a, T b) { return a < b; }
template <typename T> inline void percdown(T nums[], int target, int n) { int a = target * 2 + 1, b = a + 1, x; while (true) { x = target; if (a < n && comp(nums[x], nums[a])) x = a; if (b < n && comp(nums[x], nums[b])) x = b; if (x != target) swap<T>(nums[x], nums[target]); else break; target = x, a = x * 2 + 1, b = a + 1; } }
template <typename T> inline void percup(T nums[], int target) { int f = target - 1 >> 1; while (target > 0 && comp(nums[f], nums[target])) { swap<T>(nums[f], nums[target]); target = f; f = target - 1 >> 1; } }
template <typename T> inline void buildheap(T nums[], int n) { for (int i = n / 2; i >= 0; --i) { percdown<T>(nums, i, n); } }
template <typename T> void heapsort(T nums[], int n) { buildheap<T>(nums, n); for (int i = n - 1; i > 0; --i) { swap(nums[0], nums[i]); percdown<T>(nums, 0, i); } }
void ArrayPrint(int nums[], int n) { for (int i = 0; i < n; ++i) { printf("%2d ", nums[i]); } putchar('\n'); }
bool check_sort(int nums[], int n) { for (int i = 1; i < n; ++i) { if (nums[i] < nums[i - 1]) return false; } return true; }
bool SortTest() { freopen("luogu.out", "w", stdout); int nums[1007]; srand((unsigned int)time(NULL)); for (int i = 0; i < 1000; ++i) { for (int j = 0; j < 1000; ++j) { nums[i] = rand() % 10000; printf("%4d ", nums[i]); } putchar('\n');
heapsort<int>(nums, 1000);
if (!check_sort(nums, 1000)) return false; printf("检查通过\n"); } return true; }
int main() { if (SortTest()) printf("\n排序函数没有问题\n"); else printf("\n排序函数有错误\n"); return 0; }
|