天天看点

大顶堆的插入和删除(C语言)

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<time.h>
const int MAXN = 10000;
struct Data
{
	int id = 0;
};
struct Heap
{
	Data data[MAXN];
	int size;
	Heap()
	{
		data[0].id = _CRT_INT_MAX;
		size = 0;
	}
};
void Insert(Heap* heap,Data data)
{
	if (heap->size == MAXN -1)
	{
		printf("堆已满");
		return;
	}
	else
	{
		int index = ++heap->size;
		heap->data[index] = data;
		//默认插入到完全二叉树的最后一个位置,如果该数较大,则插入到它的子树位置
		for (index; heap->data[index].id > heap->data[index / 2].id;index = index/2)
		{
			Data temp = heap->data[index];
			heap->data[index] = heap->data[index / 2];
			heap->data[index / 2] = temp;
		}
	}
}
//取出最大值元素并删除
Data Delete(Heap* heap)
{
	if (!heap->size)
	{
		printf("堆是空的\n");
	}
	else
	{
		Data max_return = heap->data[1];
		heap->data[1] = heap->data[heap->size];//让堆顶元素暂时等于最后一个元素
		int index = 1;
		int size = heap->size;
		int ct;
		for (ct = 0; size != 0; ct++, size >>= 1);//ct为堆的层数
		while (index < pow(2, ct - 1))//
		{
			//左儿子为较大的值并且当前比左儿子小
			if (heap->data[index * 2].id > heap->data[index * 2 + 1].id && heap->data[index].id < heap->data[index * 2].id)
			{
				//交换
				Data temp = heap->data[index * 2];
				heap->data[index * 2] = heap->data[index];
				heap->data[index] = temp;
				index = index * 2;
			}
			//右儿子为较大的值并且当前比右儿子小
			else if (heap->data[index * 2].id < heap->data[index * 2 + 1].id && heap->data[index].id < heap->data[index * 2 + 1].id)
			{
				//交换
				Data temp = heap->data[index * 2 + 1];
				heap->data[index * 2 + 1] = heap->data[index];
				heap->data[index] = temp;
				index = index * 2 + 1;
			}
			//当前位置只有一个孩子
			else if (index * 2 == heap->size)
			{
				if (heap->data[index].id < heap->data[index * 2].id)
				{
					//交换
					Data temp = heap->data[index * 2];
					heap->data[index * 2] = heap->data[index];
					heap->data[index] = temp;
					index = index * 2;
				}
				else
				{
					break;
				}
			}

			else
			{
				//插到了该插的位置了
				break;
			}
		}
		heap->size--;
		return max_return;
	}
}
int main()
{
	Heap* heap = new Heap();
	srand(time(0));
	for (int i = 0; i <= 14; i++)
	{
		Data temp;
		temp.id = rand() % 100;
		Insert(heap, temp);
	}
	int max = Delete(heap).id;
	printf("%d\n", max);
	
}