#include <iostream>
using namespace std;
void sift(int a[], int k, int m)
{
int i = k;
int j = 2 * i + 1;
while (j < m-1)
{
if (j < m-1 && a[j] < a[j+1]) j++;
if (a[i] > a[j]) break;
else
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
i = j;
j = 2 * i + 1;
}
}
}
void heapsort(int a[], int n)
{
int i = 0;
int j = 0;
for (i = n/2; i>=0; i--)
sift(a, i, n);
for (j = 1; j < n; j++)
{
int temp = a[0];
a[0] = a[n-j];
a[n-j] = temp;
sift(a, 0, n-j);
}
}
int main(void)
{
int k = 0;
int a[11] = {10, 4, 9, 40, 11, 66, 32, 21, 99, 33, 6};
heapsort(a, 11);
for (k = 0; k < 11; k++)
printf ("%d\t", a[k]);
printf ("\n");
return 0;
}
阅读(758) | 评论(0) | 转发(0) |