堆排序C语言实现

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/hnujunjie/article/details/95538628

#include<stdio.h>
int main()
{
void swap(int * eleA,int * eleB);
void AdjustSort(int array[],int low,int high);
void HeapSort(int array[],int length);
int length;
scanf("%d",&length);
fflush(stdin);
int array [length];
for(int i = 0;i<length;i++)
{
scanf("%d",&array[i]);
}
HeapSort(array,length);
return 0;
}
void swap(int * eleA,int * eleB)
{
int temp;
temp = *eleA;
*eleA = eleB;
eleB = temp;
}
void AdjustSort(int array[],int low,int high)
{
//构建大顶堆
for(int f = low,i = 2
low+1;i <= high;i = 2
i+1)
{
if(i<high&&array[i] < array[i+1])
{
i++;
}
if(array[f] > array[i])
{
break;
}
else
{
swap(&array[f],&array[i]);
}
f = i;
}
}
void HeapSort(int array[],int length)
{
for(int i = (length-2)/2;i >= 0;i–)
{
//按照顺序依次构建各个子树的大顶堆
AdjustSort(array,i,length-1);
}
for(int i = length-1;i >= 0;i–)
{
//首元素和末尾元素互换
swap(&array[0],&array[i]);
//输出堆顶元素(最大值)
printf("%d ",array[i]);
//重新调整堆为大顶堆
AdjustSort(array,0,i-1);
}
}

猜你喜欢

转载自blog.csdn.net/hnujunjie/article/details/95538628