写给自己看的二叉堆(1):基本操作

也就是一棵完全二叉树。堆顶最大则为大根堆,堆顶最小则为小根堆,这里实现的是小根堆。
1.定义
用一个数组来存储数据。

typedef int eletype;

typedef struct heapstruct
{
	int capacity;
	int size;
	eletype *arr; //used for saving data
}Heap;

2.新建一个二叉堆
给二叉堆分配空间,给存储数据用的数组分配空间。

Heap *CreateHeap(int max)
{
	Heap *H;
	H = malloc(sizeof(Heap));
	if (H == NULL) {
		printf("Out of space\n");
		return NULL;
	}

	H->arr = malloc(sizeof(eletype) * (max + 1));
	if (H->arr == NULL) {
		printf("Out of space\n");
		return NULL;
	}

	H->capacity = max;
	H->size = 0;
	H->arr[0] = 0;

	return H;
}

3.插入
上滤找到合适的插入位置。

void Insert(Heap *H,  eletype data)
{
	if (H->size == H->capacity) {
		printf("Heap is full\n");
		return;
	}
	int i;
	for (i = ++H->size; data < H->arr[i / 2]; i /= 2 )
		H->arr[i] = H->arr[i / 2]; //precolate up
	H->arr[i] = data;
}

4.删除最小元素(堆顶)
为了保证删除后仍是一个完整的二叉堆,要将原堆顶以下的数据进行适当的上滤。

eletype DeleteMin(Heap *H)
{
	if (H->size == 0) {
		printf("Heap is empty\n");
		return 0;
	}
	eletype min = H->arr[1];
	eletype last = H->arr[H->size--]; //--!
	int i, child;
	for(i = 1; i * 2 <= H->size; i = child) {
		//Find smaller child
		child = i * 2;
		if (child != H->size && H->arr[child + 1] < H->arr[child])
			child++;
		//precolate one leve
		if (last > H->arr[child])
			H->arr[i] = H->arr[child];
		else
			break;
	}
	H->arr[i] = last;
	return min;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值