您的位置:首页 > 其它

基本排序算法--堆排序

2015-08-25 16:36 344 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: