堆排序实现
#include <stdio.h>
#include <time.h>
#define N 7
void swap(int a[], int m, int n)
{
int tmp;
tmp = a[m];
a[m] = a[n];
a[n] = tmp;
}
void headadjust(int a[], int i, int end)
{
int dad; //定义父节点,子节点
int son;
dad = i;
son = 2 * dad + 1;
while(son <end)
{
if(son + 1 < end && a[son] < a[son + 1])
{
son++;
}
if(a[son] > a[dad])
{
swap(a, son, dad);
}
dad = son;
son = 2 * dad + 1;
}
}
void heapsort(int a[],int len)
{
int i, n;
int end;
end = len;
for(i = end / 2.0 -1; i >= 0; i--)
{
headadjust(a, i, end);
}
end--;
while(end > 0)
{
swap(a, 0, end);
end--;
headadjust(a, 0, end);
}
}
int main()
{
int i;
int a[N];
srand((unsigned)time(NULL));
for(i = 0; i < N; i++)
{
a[i] = rand() % 100;
printf("%d ", a[i]);
}
printf("\n");
heapsort(a, N);
for(i = 0; i < N; i++)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}