#include<iostream>
using namespace std;
void HeapAdjust(int a[], int n,int i)
{
int left = 2 * i;
int right = 2 * i + 1;
int max = i;
if (left < n&&a[max] < a[left])
max = left;
if (right < n&&a[max] < a[right])
max = right;
if (max != i)
{
int temp = a[max];
a[max] = a[i];
a[i] = temp;
HeapAdjust(a, n, max);
}
}
void BuildHeap(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
HeapAdjust(a, n, i);
}
void HeapSort(int a[], int n)
{
BuildHeap(a, n);
for (int i = n - 1; i > 0; i--)
{
int temp = a[0];
a[0] = a[i];
a[i] = temp;
HeapAdjust(a, i, 0);
}
}
int main()
{
int array[] = { 34, 65, 12, 43, 67, 5, 78, 10, 3, 70 };
int len = sizeof(array) / sizeof(int);
cout << "the original array are:" << endl;
for (int k = 0; k < len; k++)
cout << array[k] << " ";
cout << endl;
HeapSort(array, len);
cout << "The sorted array are:" << endl;
for (int k = 0; k<len; k++)
cout << array[k] << ",";
cout << endl;
return 0;
}
基本排序算法--堆排序
最新推荐文章于 2022-12-23 14:44:16 发布