Description
编写程序堆排序算法。按照非递减排序,测试数据为整数。
Input
第一行是待排序数据元素的个数; 第二行是待排序的数据元素。
Output
一趟堆排序的结果
Sample Input
行数 | 数据 |
---|---|
1 | 10 |
2 | 14 12 20 18 22 41 50 36 19 23 |
代码
#include<iostream>
using namespace std;
void sift(int a[], int low, int high)
{
int i = low, j = 2 * i;
int temp = a[low];
while (j <= high)
{
while (j < high&&a[j] > a[j + 1])
j++;
if (temp > a[j])
{
a[i] = a[j];
i = j;
j = i * 2;
}
else break;
}
a[i] = temp;
}
void heap(int a[], int n)
{
int i, temp;
for (i = n / 2; i >= 1; i--)
{
sift(a, i, n);
}
}
int main()
{
int a[100], i, n;
cin >> n;
for (i = 1; i <= n; i++)
cin >> a[i];
heap(a, n);
for (i = 1; i <= n; i++){
cout << a[i] << ' ';
}
return 0;
}