堆的算法

来源:互联网 发布:手机淘宝5星好评 编辑:程序博客网 时间:2024/04/29 16:02

#include<iostream>
using namespace std;
#include<time.h>
struct Heap

 int * heap;
 int len;
 int MaxSize;
};

void InitHeap( Heap &HBT)
{
 HBT.MaxSize=10;
 HBT.heap=new int[HBT.MaxSize];
 if(!HBT.heap)
 {
  cout<<"动态分配失败,退出运行"<<endl;
  exit(1);
 }
 HBT.len=0;
}
void ClearHeap( Heap &HBT )
{
 if(HBT.heap!=NULL)
 {
  delete [] HBT.heap;
  HBT.heap=NULL;
  HBT.len=0;
  HBT.MaxSize=0;
 }

}

bool EmptyHeap(Heap &HBT)
{
 return (bool)HBT.len;
}

void InsertHeap(Heap&HBT,int item)
{
 if(HBT.len==HBT.MaxSize)
 {
  int k=sizeof(int);
  HBT.heap=(int *)realloc(HBT.heap,2*HBT.MaxSize);
  if(HBT.heap==NULL)
  {
   cout<<"动态分配失败,退出程序"<<endl;
   exit(1);
  }
  HBT.MaxSize=2*HBT.MaxSize;
 }
 int i=HBT.len;
 while(i!=0)
 {
  int j=(i-1)/2;
  if(item>=HBT.heap[j])break;
  HBT.heap[i]=HBT.heap[j];
  i=j;
 }
 HBT.heap[i]=item;
 HBT.len++;
}

int   HeapDelete(Heap &HBT)
{
 if(HBT.len==0)
 {
  cout<<"堆为空"<<endl;
  exit(1);
 }
 int temp=HBT.heap[0];
 HBT.len--;
 int x=HBT.heap[HBT.len];
 int i=0;
 int j=1;
 while(j<=HBT.len-1)
 {
  if(j<HBT.len-1 && HBT.heap[j]>HBT.heap[j+1])

   j++;
  if(x<=HBT.heap[j])
   break;
  HBT.heap[i]=HBT.heap[j];
  i=j;
  j=2*i+1;
 }
 HBT.heap[i]=x;
 return temp;

}
void main()
{
 srand((unsigned)time(NULL));
 Heap h;
 InitHeap(h);
 for(int i=0;i<10;i++)
 {   int y=rand()%100;
 InsertHeap(h,y);
 cout<<y<<"  ";

 }
 cout<<endl;
 while(EmptyHeap(h))
 {
  int x;
  x=HeapDelete(h);
  cout<<x<<" ";
 }

}

原创粉丝点击