堆(以小顶堆为例)

//数据结构-堆,用C++类实现,这里以小顶堆为例,所谓的堆,是一种以完全二叉树为基础的数据结构,二话不说,上代码;
 
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<vector>
#include<list>
 
using namespace std;
 
class Heap
{
	size_t maxsize;
	size_t len;
	int *arr;
public:
	Heap() :maxsize(10), len(0), arr(new int[maxsize]){}
	~Heap()
	{
		if (arr != nullptr)
		{
			delete arr;
			arr = nullptr;
			maxsize = len = 0;
		}
	}
	void insert(int data)
	{
		if (maxsize < len)//内存不足够
		{
			maxsize += (maxsize >> 1)>1 ? maxsize >> 1 : 1;
			int *temp = new int[maxsize];
 
			if (arr != nullptr)
			{
				memcpy(temp, arr, sizeof(int)*len);
				delete[]arr;
				arr = temp;
			}
			arr[len++] = data;
			size_t index = len - 1;//data的下标
			int mytemp;
			while (index > 0)//不是根节点
			{
				//父节点的下标   (index-1)/2
				if (arr[index] < arr[(index - 1) / 2])//父节点大于儿子
				{
					//父节点大于儿子 交换
					mytemp = arr[index];
					arr[index] = arr[(index - 1) / 2];
					arr[(index - 1) / 2] = mytemp;
 
					index = (index - 1) / 2;//继续往上调整
				}
				else
				{
					break;
				}
			}
		}
	}
 
	int pop()//删除
	{
		if (arr == nullptr || len == 0) throw"heap is NULL";
		int mytemp = arr[0];
		size_t index, index1, index2, temp;
		arr[0] = arr[--len];
		index = 0;
		while (index < len)
		{
			index1 = index * 2 + 1;//左孩子
			index2 = index * 2 + 2;//右孩子
			//  1.有右孩子 必定会有左孩子
			//  2.有左边未必有右孩子
			if (index1 >= len)
				break;
 
			else if (index2 >= len)
			{
				if (arr[index1] < arr[index])
				{
					//左孩子调整上去
					temp = arr[index];
					arr[index] = arr[index1];
					arr[index1] = temp;
				}
				break;//
			}
			else//左右孩子都有
			{
				if (arr[index1] > arr[index2])//左孩子大于右孩子
				{
					//放右孩子上去
					temp = arr[index];
					arr[index] = arr[index2];
					arr[index2] = temp;
					//然后对右边进行调整
					index = index2;//右孩子作为新的要调整的位置
				}
				else//左孩子小于右孩子
				{
					temp = arr[index];
					arr[index] = arr[index1];
					arr[index1] = temp;
					index = index1;//左孩子
				}
			}
		}
		return mytemp;
	}
 
};
 
int main()
{
	srand((unsigned)time(nullptr));
	Heap myheap;
	for (int i = 0; i < 10; ++i)
	{
		int x=rand() % 100;
		myheap.insert(x);
	}
	for (int i = 0; i < 10; ++i)
	{
		cout << myheap.pop() << '\t';
	}
 
	cin.get();
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

淮城一只猫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值