//Heap_sort
#include <stdio.h>
int Left(int i)//return left child
{
return 2*i+1;
}
int Right(int i)//return right child
{
return 2*i+2;
}
void swap(int *p1,int *p2)
{
int temp;
temp=*p1;
*p1=*p2;
*p2=temp;
}
//keep the character of the max_heap
void Max_Heapify(int A[],int i,int n)
{
int l,r,largest;
l=Left(i);
r=Right(i);
if(l<=n&&A[l]>A[i])
largest=l;
else
largest=i;
if(r<=n&&A[largest]<A[r])
largest=r;
if(largest!=i)
{
swap(&A[largest],&A[i]);
Max_Heapify(A,largest,n);
}
}
//Bui ld a max_heap
void Build_Max_Heap(int A[],int n)
{
for(int i=n/2;i>=0;--i)
Max_Heapify(A,i,n);
}
//The Heap_sort algorithm
void Heap_Sort(int A[],int n)
{
Build_Max_Heap(A,n);
for(int i=n;i>=1;--i)
{
swap(&A[i],&A[0]);
n=n-1;
Max_Heapify(A,0,n);
}
}
void main()
{
int A[]={1,3,2,6,5,4,7,8};
Heap_Sort(A,7);
for(int i=0;i<8;i++)
printf("%d ",A[i]);
}
堆排序C语言实现 算法导论
最新推荐文章于 2023-12-10 17:31:00 发布