c++ 堆排序
强烈推荐视频: 堆排序(heapsort)
代码:
#include <iostream>
#include <stdlib.h>
using namespace std;
void heapify(int tree[], int n, int i)
{
if (i >= n)
return;
int c1 = 2 * i + 1;
int c2 = 2 * i + 2;
int max = i;
if (c1 < n && tree[c1] > tree[max])
max = c1;
if (c2 < n && tree[c2] > tree[max])
max = c2;
if (max != i)
{
swap(tree[max], tree[i]);
heapify(tree, n, max);
}
}
void build_head(int tree[], int n)
{
int last_node = n - 1;
int parent = (last_node - 1) / 2;
for (int i = parent; i >= 0; i--)
{
heapify(tree, n, i);
}
}
void heap_sort(int tree[], int n)
{
build_head(tree, n);
for (int i = n - 1; i >= 0; i--)
{
swap(tree[i], tree[0]);
heapify(tree, i, 0);
}
}
int main()
{
int tree[] = {2, 5, 3, 1, 10, 4};
heap_sort(tree, 6);
for (int i = 0; i < 6; i++)
cout << tree[i] << " ";
cout << endl;
system("pause");
return 0;
}

![c++ 堆排序
[编程语言教程]](https://www.zixueka.com/wp-content/uploads/2024/02/1706717587-534c27f8897146c.jpg)
