如何用小堆打印数组的升序?

堆的实现: 

#include <iostream >
using namespace std;
#include <assert.h>

typedef struct Heap
{
	int* array;
	int size;
	int capacity;
}HP;

void HeapInit(HP* hp)
{
	hp->array = nullptr;
	hp->capacity = hp->size = 0;
}

void HeapDestroy(HP* hp)
{
	assert(hp);
	free(hp->array);
	hp->array = nullptr;
	hp->capacity = hp->size = 0;
}

void swap(int* hp1, int* hp2)
{
	int tmp = *hp1;
	*hp1 = *hp2;
	*hp2 = tmp;
}

//小堆
void adjustUp(int* array, int child)
{
	int parent = (child - 1) / 2;

	while (child>0)
	{
		if (array[child] < array[parent])
		{
			swap(&(array[child]), &(array[parent]));
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(HP* hp, int x)
{
	assert(hp);
	if (hp->size == hp->capacity)
	{
		//扩容
		int newCapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		int* newA =(int*) realloc(hp->array, sizeof(int) * newCapacity);
		if (newA==nullptr)
		{
			printf("realloc fail");
		}
		hp->capacity = newCapacity;
		hp->array = newA;
	}
	hp->array[hp->size] = x;
	hp->size++;

	adjustUp(hp->array,hp->size-1);
}

int HeapTop(HP* hp)
{
	assert(hp);
	assert(hp->size > 0);
	return hp->array[0];
}

bool HeapEmpty(HP* hp)
{
	assert(hp);
	return hp->size == 0;
}

int HeapSize(HP* hp)
{
	assert(hp);
	return hp->size;
}

void adjustDown(int* array, int parent, int size)
{
	//默认最小孩子为左孩子
	int child = parent * 2 + 1;

	//判断
	while (child < size)
	{
		//确保child为最小孩子
		if (child + 1 < size && array[child + 1] < array[child])
		{
			child = child + 1;
		}

		if (array[child] < array[parent])
		{
			swap(&(array[child]), &array[parent]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPop(HP* hp)
{
	assert(hp);
	assert(hp->size > 0);
	swap(&(hp->array[0]), &(hp->array[hp->size - 1]));
	hp->size--;

	adjustDown(hp->array,0,hp->size);
}

 题目需要的代码:

int main()
{
	HP hp;
	HeapInit(&hp);
	int a[] = { 27,15,19,18,28,34,65,49,25,37 };
	for (int i = 0; i < sizeof(a) / sizeof(int); i++)
	{
		HeapPush(&hp, a[i]);
	}
	while (!HeapEmpty(&hp))
	{
		cout << HeapTop(&hp) << " " ;
		HeapPop(&hp);
	}
	HeapDestroy(&hp);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值