堆排序

来源:互联网 发布:mac aecc2015 编辑:程序博客网 时间:2024/05/20 10:22

 

#include "stdio.h"
typedef int EType;

void adjustHeap(EType a[],int start,int n)
{
  int i=start,j,s;
  EType tmp;
  tmp=a;
  j=2*i+1;
  s=i;
  while(j<=n)
  {
  if(j+1<=n && a[j+1]>a[j])
   j=j+1;
  if(a[j]>a[s])
  {
   a[s]=a[j];
   s=  j;
   j=j*2+1;
  }
  else
  {
   break;
  }
  }
  a[s]=tmp;
}
void createHeap(EType a[],int n)
{
      int i,j,s;
      EType tmp;
      for(i=(n-1)/2;i>=0;i--)
      {
  tmp=a;
  j=2*i+1;
  s=i;
  while(j<=n)
  {
  if(j+1<=n && a[j+1]>a[j])
   j=j+1;
  if(a[j]>a[s])
  {
   a[s]=a[j];
   s=  j;
   j=j*2+1;
  }
  else
  {
   break;
  }
  }
  a[s]=tmp;
      }
}
EType outHeap(EType a[],int n)
{
EType tmp=a[0];
int  i,j,s;
if (n<1) return NULL;
a[0]=a[n-1];
if(n>1)
       adjustHeap(a,0,n-1);
return tmp;
}
void InsertHeap(EType a[],EType t,int n)
{
int i,j;
n++;
a[n-1]=t;
i=(n-1)/2;
while(i>=0)
{
  adjustHeap(a,i,n);
  if(i>0)
  {
   i=(i-1)/2;
  }
  else
   break;
}
}
EType getMax(EType a[],int n)
{
if (n<1) return NULL;
return a[0];
}
main()
{
     EType a[20]={1,5,3,9,6};
     int i,j,n;
    /* n=sizeof(a)/sizeof(EType);*/
    n=5;
     createHeap(a,n);
     InsertHeap(a,10,n);
     n++;
     while(n>0)
     {
printf("%2d",outHeap(a,n));
n--;
     }
}

原创粉丝点击