浙大数据结构笔记-最大堆

最大堆

最大堆的存储结构-完全二叉树,数组存储

typedef struct HeapStruct *MaxHeap;
struct HeapStruct{
	ElementType *Elements;
	int Size;
	int Capacity;
}; 

最大堆操作

MaxHeap Create( int maxsize ){
	MaxHeap H = (MaxHeap)malloc(sizeof(struct HeapStruct));
	H->Elements = (ElementType*)malloc( (MaxSize+1)*sizeof(ElementType));
	H->Size = 0;
	H->Capacity = maxsize;
	H->Elements[0] = MaxData;
	return H;
}

void Insert ( MaxHeap H, ElementType item ){
	int i;
	if ( IsFull(H) ) {
		printf("The max heap is full.\n");
		return;
	}
	i = ++H->Size;
	for ( ; H->Elements[i/2] < item; i/=2 ) 
		H->Elements[i] = H->Elements[i/2];
	H->Elements[i] = item;
}

ElementType DeleteMax ( MaxHeap H ){
	int Parent, Child;
	ElementType MaxItem, temp;
	if ( IsEmpty(H) ) {
		printf("The max heap is empty.\n");
		return;
	}
	MaxItem = H->Elements[1];  //take out the maximum data
	temp = H->Elements[H->Size--]; //take out the last data of the heap
	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 MaxItem;
}

bool IsFull ( MaxHeap H ){
	if ( H->Size == H->Capacity )
		return true;
	else 
		return false;
}

bool IsEmpty ( MaxHeap H ){
	if ( H->Size == 0 ) 
		return true;
	else 
		return false;
}

//level order traversal
void LevelOrderTraversal ( MaxHeap H ) {
	int i;
	printf("Level Order Search: ");
	for ( i=1; i<=H->Size; i++){
		printf("%5d", H->Elements[i]);
	}
	printf("\n");
}

参考自
https://www.icourse163.org/learn/ZJU-93001?tid=120001#/learn/content

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值