`

二叉堆

阅读更多
#include <stdio.h>
#include <stdlib.h>

/**
 * 经常使用 heap 实现 优先级队列
 */

#define MAX_SIZE 100

#define True 1
#define False 0
typedef short Boolean;
typedef struct node* pNode;
struct node{
	int data;
};

pNode heap[MAX_SIZE+1]; /// index of first element is 1
int size;
Boolean isFull();
Boolean isEmpty();
void insert(pNode);
pNode delete(); ///// delete the biggest node
void print();
pNode getMax();


#include "deap.h"

void print()
{
	if(isEmpty()){
		return;
	}
	
	int i = 1;
	while(i <= size){
		printf("%d ", heap[i++]->data);
	}
	printf("\n");
}

Boolean isFull()
{
	if(size == MAX_SIZE+1) return True;
	return False;
}

Boolean isEmpty()
{
	if(size == 0) {
		printf("Empty deap\n");
		return True;
	}
	return False;
}

// while 循环从最大堆的 新叶子结点 开始,
// 沿着到根结点的路径,直到根结点
// 使其父结点 i/2 的值 不小于 要插入的值
void insert(pNode elem)
{
	
	if(isFull(size)){
		printf("sizeo space\n");
		return;
	}
	
	int i = ++size;
	while(i!=1 && elem->data > heap[i/2]->data){ /// 把父结点移动到其子结点位置
		heap[i] = heap[i/2];
		i /= 2;
	}
	
	heap[i] = elem;
}

/// 删除根元素,然后把最后一个元素设为根元素,
/// 接着进行调整,使之复合最大堆/最小堆
pNode delete(){
	pNode res = 0;
	if(isEmpty()){
		return 0;
	}
	
	res = heap[1]; /// 得到最大元素
	
	pNode last = heap[size--]; ///  得到最后一个元素
	
	//heap[1] = last;
	
	int parent = 1;  //// 从新的 根元素 开始
	int child = 2; /// 新的根元素的 孩子
	
	while(child <= size){
		if(child < size && heap[child]->data < heap[child+1]->data){   ////// 比较兄弟结点,取较大者的下标
			child++;
		}
		if(heap[child]->data > last->data){  //// 如果 较大的子结点 大于 新的 根结点
			heap[parent] = heap[child];       //// 那么把 该子结点 移动到 父结点位置
			parent = child;                  /// 当前子结点设为 起点 重新开始移动
			child *= 2;
		}else{
			break;
		}
	}
	
	heap[parent] = last;
	return res;
}

pNode getMax(){
	if(!isEmpty()){
		return heap[1];
	}
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics