首页 > 代码库 > Heapsort

Heapsort

Basic plan for in-place sort.

a.Create max-heap with all N keys.

b.Repeatedly remove the maximum key.

Procesure

<span style="font-size:10px;">#include<stdio.h>
#include<stdlib.h>

int N=11;
char a[]={' ','S','E','E','L','M','O','P','R','S','T','X'};

int less(int x,int y)
   {
	return a[x]<=a[y];
}
void exchange(char a[],int i,int j)
{
	char temp;
	temp=a[i];
	a[i]=a[j];
	a[j]=temp;
}
void swim(int k)
{
	while(k>1&&less(k/2,k))
	{
		exchange(a,k/2,k);
		k=k/2;
	}
}
void sink(char a[],int k,int N)
{
	while(2*k<=N)
	{
		int j=2*k;
		if(j<N&&less(j,j+1))
			j++;
		if(!less(k,j))
			break;
		exchange(a,k,j);
		k=j;
	}
}
void insert(char x)
{
	a[++N]=x;
	swim(N);
}
char delMAX()
{
	char max=a[1];
	exchange(a,1,N--);
	sink(a,1,N);
	return max;
}
void print()
{
	int i;
	for(i=1;i<=11;i++)
	{
		printf("%c",a[i]);
	}
}
void heapsort(char a[])
{
	int k;
	for(k=N/2;k>=1;k--)
		sink(a,k,N);
	while(N>1)
	{
		exchange(a,1,N--);
		sink(a,1,N);
	}
}
int main()
{
	heapsort(a);
	print();
	return 0;
}</span>

Output:

EELMOPRSSTX

Heapsort