#include <iostream>
using namespace std;
void percDown(int *q, int l, int r) {
int i = l, j = 2 * i + 1;
while(j <= r) {
if(j + 1 <= r && q[j] < q[j + 1]) j = j + 1;
if(q[i] < q[j]) swap(q[i], q[j]);
else break;
i = j, j = 2 * j + 1;
}
}
void buildHeap(int *q, int len) {
for(int i = len / 2; i >= 0; i--)
percDown(q, i, len - 1);
}
void heapSort(int *q, int len) {
while(len--) {
swap(q[0], q[len]);
percDown(q, 0, len - 1);
}
}
int main() {
int q[] = {5, 1, 10, 7, 2, 3, 0};
int len = sizeof(q) / sizeof(int);
buildHeap(q, len);
heapSort(q, len);
cout << endl;
for(int i = 0; i < len; i++)
cout << q[i] << endl;
return 0;
}
堆排序
最新推荐文章于 2024-09-04 21:39:45 发布