堆排序算法
参考博客
#include <iostream>
#include <ctime>
using namespace std;
void heapify(int tree[], int N, int no)
{
while (no >= 0 && no < N)
{
int max = no;
if (2 * no + 1 < N && tree[2 * no + 1] > tree[max])
max = 2 * no + 1;
if (2 * no + 2 < N && tree[2 * no + 2] > tree[max])
max = 2 * no + 2;
if (max == no)
{
return;
}
else
{
int temp = tree[max];
tree[max] = tree[no];
tree[no] = temp;
no = max;
}
}
}
void buildHeap(int tree[], int N)
{
if (N <= 1)
return;
for (int i = (N - 2) / 2; i >= 0; i--)
{
heapify(tree, N, i);
}
}
void heapSort(int tree[], int N)
{
for (int i = N - 1; i >= 0; i--)
{
int temp = tree[0];
tree[0] = tree[i];
tree[i] = temp;
heapify(tree, i, 0);
}
}
int main()
{
srand((unsigned int)time(NULL));
int s[10];
cout << "随机数生成" << endl;
for (int i = 0; i < 10; i++)
{
s[i] = rand() % 10;
cout << s[i] << "\t";
}
cout << endl;
cout << "堆化" << endl;
buildHeap(s, 10);
for (int i = 0; i < 10; i++)
{
cout << s[i] << "\t";
}
cout << endl;
cout << "堆排序" << endl;
heapSort(s, 10);
for (int i = 0; i < 10; i++)
{
cout << s[i] << "\t";
}
cout << endl;
system("pause");
return 0;
}