大根堆实现

大根堆是根节点的值都大于子树的值,左右子树又是一个大根堆
实现
头文件,堆结构

#include<iostream>
using namespace std;

#define MAXVALUE INT_MAX

typedef int ElemtType;

typedef struct Heap{
	ElemtType* heap;//大根堆,顺序存储
	int size;   //堆中元素个数
	int capacity;//最大容量
}*maxHeap;

maxHeap createMaxHeap(int MaxSize);
bool isEmpty(maxHeap heap);
bool isFull(maxHeap heap);
ElemtType top(maxHeap heap);
void pop(maxHeap &heap);
void insert(maxHeap &heap,ElemtType key);

方法定义

#include "stdafx.h"
#include<iostream>
#include"maxHeap.h"



int _tmain(int argc, _TCHAR* argv[])
{
	return 0;
}


maxHeap createMaxHeap(int maxSize){
	maxHeap maxHeap  = new Heap;
	maxHeap->heap = new ElemtType[maxSize];
	memset(maxHeap->heap,0,maxSize);
	maxHeap->capacity = maxSize;
	maxHeap->size = 0;
	maxHeap->heap[0] = MAXVALUE;
	return maxHeap;
	
}
bool isEmpty(maxHeap heap) {
	return heap->size == 0;
}

bool isFull(maxHeap heap) {
	return heap->size == heap->capacity;
}

void insert(maxHeap &heap,ElemtType key) {
	if(isFull(heap)) {
		cout << "堆已满"<<endl;
		return;
	}
	int i = ++heap->size;
	for(;heap->heap[i/2] < key ; i/=2) {

		heap->heap[i] = heap->heap[i/2];
	}
	heap->heap[i] = key;
}

ElemtType top(maxHeap h) {
	if(isEmpty(h)){
		cout << "堆空"<<endl;
		return -1;
	}
	return h->heap[1];
}

void pop(maxHeap &h) {
	if(isEmpty(h)) {
		cout << "堆空"<<endl;
		return;
	}
	int tmp = h->heap[h->size];
	h->size--;
	int parent,child;
	for(parent = 1;parent * 2 <= h->size;parent = child) {
		int lchild = 2 * parent;
		if(lchild + 1 <= h->size && h->heap[lchild] < h->heap[lchild+1]){
			child = lchild+1;
		}
		if(tmp > h->heap[child]) break;
		else{
			h->heap[parent] = h->heap[child];
		}

	}
	h->heap[parent] = tmp; 
}

void levelTraverse(maxHeap h) {
	if(isEmpty(h)) return;
	for(int i = 1;i<=h->size;i++){
		cout<<h->heap[i]<<" ";
	}
	cout<<endl;
}

int main() {
	int n;
	maxHeap heap = createMaxHeap(100);
	insert(heap,7);
	insert(heap,9);
	insert(heap,19);
	insert(heap,5);
	insert(heap,1);
	levelTraverse(heap);
	cout << top(heap) <<endl;
	pop(heap);
	levelTraverse(heap);
	cin >> n;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值