百度了一下肉眼没看见太完整的代码。
/*Texas*/
#include<iostream>
#define MinData -2147483648
using namespace std;
typedef struct HeapStruct *MinHeap;
struct HeapStruct
{
int *Elements;
int Size;
int Capacity;
};
MinHeap Create(int MaxSize)
{
MinHeap H=(MinHeap)malloc(sizeof(struct HeapStruct));
// MinHeap H=(MinHeap)malloc(sizeof(MinHeap));
H->Elements=(int*)malloc((MaxSize+1)*sizeof(int));
H->Size=0;
H->Capacity=MaxSize;
H->Elements[0]=MinData;
return H;
}
bool IsFull(MinHeap H)
{
return (H->Capacity==H->Size);
}
MinHeap Insert(MinHeap H,int item)
{
int i;
if(IsFull(H))
{
cout<<"the Heap is full,fail to insert"<<endl;
return H;
}
i=++H->Size;
for(;H->Elements[i/2]>item;i/=2) H->Elements[i]=H->Elements[i/2];
H->Elements[i]=item;
return H;
}
bool IsEmpty(MinHeap H)
{
return (H->Size==0);
}
int DeleteMin(MinHeap H)
{
int Parent,Child;
int MinItem,temp;
if(IsEmpty(H))
{
cout<<"the Heap is Empty,fail to delete"<<endl;
return 0;
}
MinItem=H->Elements[1];
temp=H->Elements[H->Size--];
for(Parent=1;Parent*2<=H->Size;Parent=Child)
{
Child=Parent*2;
if((Child!=H->Size)&&(H->Elements[Child]>H->Elements[Child+1])) Child++;
if(temp<=H->Elements[Child]) break;
else H->Elements[Parent]=H->Elements[Child];
}
H->Elements[Parent]=temp;
return MinItem;
}
MinHeap BuildMinHeap(MinHeap H)
{
int Parent,Child,i;
int temp;
for(i=H->Size/2;i>0;i--)
{
temp=H->Elements[i];
for(Parent=i;Parent*2<=H->Size;Parent=Child)
{
Child=Parent*2;
if((Child!=H->Size)&&(H->Elements[Child]>H->Elements[Child+1])) Child++;
if(temp<=H->Elements[Child]) break;
else H->Elements[Parent]=H->Elements[Child];
}
H->Elements[Parent]=temp;
}
return H;
}
MinHeap Construction(int* ElementsInput,int n)
{
cout<<"there are "<<n<<" elements"<<endl;
MinHeap H=Create(n);
H->Size=n;
for(int i=0;i<=n;i++)
{
H->Elements[i]=ElementsInput[i];
}
return H;
}
int main()
{
int n;
cout<<"Please input the number as INT:";
cin>>n;
cout<<"Plesae input these data as INT:";
MinHeap H=Create(n);
H->Size=n;
for(int i=1;i<=n;i++)
{
cin>>H->Elements[i];
}
H->Elements[0]=MinData;
H=BuildMinHeap(H);
cout<<"there are "<<H->Size<<" elements"<<endl;
cout<<"the Output is:";
for(int i=1;i<=H->Size;i++)
{
cout<<H->Elements[i]<<' ';
}
cout<<endl;
cout<<"Deletemin:"<<DeleteMin(H)<<endl;
int k;
cout<<"insert,please input an INT:";
cin>>k;
H=Insert(H,k);
for(int i=1;i<=n;i++)
{
cout<<H->Elements[i]<<' ';
}
return 0;
}
参见陈越的数据结构,里面是最大堆,我调整成最小堆并完善了输入操作。
实在不理解可参考
(最后抛弃了construction函数)
博客园