大根堆是根节点的值都大于子树的值,左右子树又是一个大根堆
实现
头文件,堆结构
#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;
}