/******堆排序实现*******/ #include<iostream> #include<cstring> #define N 11 using namespace std; void HeapAdjust(int a[], int s, int m) { int rc = a[s]; for (int j = 2 * s; j <= m; j *= 2) { if (j < m&&(a[j] < a[j + 1])) ++j; if (rc>a[j])break; a[s] = a[j]; s = j; } a[s] = rc; } void HeapSort(int a[],int len) { for (int i = len / 2; i > 0; --i) HeapAdjust(a, i, len); for (int i = len; i > 1; --i) { static int count = 0; int temp = a[1]; a[1] = a[i]; a[i] = temp; cout << "第" << ++count << "趟:"; for (size_t j = 1; j != N; j++) cout << a[j] << " "; cout << endl; HeapAdjust(a, 1, i - 1); } } int main() { int a[N] = {0}; for (size_t i = 1; i != N; i++) cin >> a[i]; HeapSort(a,N-1); cout << "排好后结果为:" << endl; for (size_t i = 1; i != N; i++) cout << a[i] << " "; return 0; }
堆排序
最新推荐文章于 2023-09-21 13:21:58 发布