作者:林海书6758 | 来源:互联网 | 2023-09-09 16:04
#include
#include
#define MAXSIZE 20
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct
{
ElemType heapArray[MAXSIZE];
int length;
}MinHeap;
Status Init_heapArray(MinHeap * M,int Number)
{
ElemType data;
for(int i=0;i {
scanf("%d",&data);
M->heapArray[i]=data;
M->length++;
}
return OK;
}
Status Init_MinHeap(MinHeap * M)
{
int Number;
M->length=0;
printf("请输入数组的元素个数:\n");
scanf("%d",&Number);
printf("请输入%d个数据:\n",Number);
Init_heapArray(M,Number);
return OK;
}
int MinHeap_Leftchild(int pos)
{
return 2*pos+1;
}
int MinHeap_Rightchild(int pos)
{
return 2*pos+2;
}
int MinHeap_Parent(int pos)
{
return (pos-1)/2;
}
void MinHeap_SiftDown(MinHeap * M,int left)
{
int i=left;
int j=MinHeap_Leftchild(i);
ElemType temp=M->heapArray[i];
while(jlength)
{
if((jlength-1)&&(M->heapArray[j]>M->heapArray[j+1]))
{
j++;
}
if(temp>M->heapArray[j])
{
M->heapArray[i]=M->heapArray[j];
i=j;
j=MinHeap_Leftchild(j);
}
else
{
break;
}
}
M->heapArray[i]=temp;
}
void Create_MinHeap(MinHeap * M)
{
for(int i=M->length/2-1;i>=0;i--)
{
MinHeap_SiftDown(M,i);
}
}
void MinHeap_SiftUp(MinHeap * M,int position)
{
int temppos=position;
ElemType temp=M->heapArray[temppos];
while((temppos>0) && (M->heapArray[MinHeap_Parent(temppos)]>temp))
{
M->heapArray[temppos]=M->heapArray[MinHeap_Parent(temppos)];
temppos=MinHeap_Parent(temppos);
}
M->heapArray[temppos]=temp;
}
void Swap(MinHeap * M,ElemType data1,ElemType data2)
{
ElemType temp;
temp=M->heapArray[data1];
M->heapArray[data1]=M->heapArray[data2];
M->heapArray[data2]=temp;
}
Status MinHeap_Delete(MinHeap * M)
{
if(M->length==0)
{
printf("不能删除,堆已空!\n");
return ERROR;
}
else
{
Swap(M,0,--M->length);
if(M->length>1)
{
MinHeap_SiftDown(M,0);
}
}
}
void Print(MinHeap * M)
{
for(int i=0;ilength;i++)
{
printf("%d ",M->heapArray[i]);
}
printf("\n");
}
int main()
{
MinHeap M;
Init_MinHeap(&M);
printf("输出先前元素:\n");
Print(&M);
Create_MinHeap(&M);
printf("输出最小堆的元素:\n");
Print(&M);
printf("删除最小堆里的最小值:\n");
MinHeap_Delete(&M);
printf("输出删除后的元素:\n");
Print(&M);
return 0;
}