堆的算法

HeadMain.h

 

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

 

 

Heap.h

 

typedef int Elemtype;
class CHeap
{
public:
 Elemtype  *m_heap;
 int       m_len;
 int       m_MaxSize;
 CHeap();
    ~CHeap();
 void InitHeap(CHeap &HBT);
 void ClearHeap(CHeap &HBT);
 bool IsEmpty( CHeap &HBT);
 void InsertHeap( CHeap & HBT, Elemtype item);
 Elemtype  DeleteHeap(CHeap &HBT);
 
};

Heap.cpp

 

#include"HeadMain.h"
CHeap::CHeap()
{
  
}
CHeap::~CHeap()
{

}
void CHeap::InitHeap(CHeap &HBT)
{
 HBT.m_MaxSize=10;
 HBT.m_heap = new  Elemtype[HBT.m_MaxSize];
 if(!HBT.m_heap)
 {
    cout<<"动态分配失败,退出程序"<<endl;
    exit(1);
 }
 HBT.m_len=0;
}
void CHeap::ClearHeap(CHeap &HBT)
{
 if(HBT.m_heap!=NULL)
 {
  delete[] HBT.m_heap;
  HBT.m_heap=NULL;
  HBT.m_len=0;
  HBT.m_MaxSize=0;
 }
}
bool CHeap::IsEmpty( CHeap &HBT)
{
 return (bool)HBT.m_len;
}
void CHeap::InsertHeap( CHeap & HBT, Elemtype item)
{
 if(HBT.m_len==HBT.m_MaxSize)
 {
     int k=sizeof(Elemtype);
  HBT.m_heap=(Elemtype*)realloc(HBT.m_heap,2*HBT.m_MaxSize*k);
  if(HBT.m_heap==NULL)
  {
    cout<<"动态分配失败,退出程序"<<endl;
    exit(1);
  }
  HBT.m_MaxSize=2*HBT.m_MaxSize;
 }
 int  i=HBT.m_len;
 while(i!=0)
 {
   int j=(i-1)/2;
   if(item>=HBT.m_heap[j])break;
   HBT.m_heap[i]=HBT.m_heap[j];
   i=j;
    }
 HBT.m_heap[i]=item;
 HBT.m_len++;
}
Elemtype  CHeap::DeleteHeap(CHeap &HBT)
{
 if(HBT.m_len==0)
 {
   cout<<"堆为空,退出程序"<<endl;
   exit(1);
 }
 Elemtype  temp=HBT.m_heap[0];
 HBT.m_len--;
 if(HBT.m_len==0)return temp;
 Elemtype  x=HBT.m_heap[HBT.m_len];
 int i=0;
 int j=0;
 while(j<=HBT.m_len-1)
 {
  if(j<HBT.m_len-1  && HBT.m_heap[j]>HBT.m_heap[j+1])
  j++;
  if(x<=HBT.m_heap[j]) break;
  HBT.m_heap[i]=HBT.m_heap[j];
  i=j;
  j=2*i+1;
 }
 HBT.m_heap[i]=x;
 
    return temp;
}
 

main.cpp

 

#include"HeadMain.h"
void main()
{
 CHeap   h;
    //CHeap  *heap = new CHeap();
 h.InitHeap(h);
 int a[10]={23,45,12,34,76,90,88,55,9,11};
 for(int i=0;i<10;i++)
 h.InsertHeap(h,a[i]);

 while(h.IsEmpty(h))
 {
  cout<<h.DeleteHeap(h)<<endl;
 
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值