堆排序中构造最大堆C/C++

17 篇文章 1 订阅
9 篇文章 0 订阅

在堆排序算法中,我们使用的是最大堆。下面的代码是给定一组数,构造一个最大堆。left(heap, location)和right(heap, location)分别返回数组heap中location的左右孩子的索引。max_heapify(heap, i)是确保heap数组的i的左右孩子都满足最大堆化。bulid_max_heap(heap)将heap数组构造一个最大堆。

/*
构造一个NUM个数最大堆;
*/
#include<iostream>
#include<ctime>
using namespace std;

const int NUM = 10;

void print(int p[] , int n)
{
	for (int i = 1; i <= n; i++)
	{
		cout << "heap[" << i << "] = " << p[i] << endl;
	}
}

int left(int heap[] , int i)
{
	return 2 * i;
}

int right(int heap[] , int i)
{
	return 2 * i + 1;
}

void max_heapify(int heap[], int location)
{
	int largest = 0, l, r, temp;
	l = left(heap, location);
	r = right(heap, location);

	if (l <= NUM && heap[l] > heap[location])
	{
		largest = l;
	}
	else
		largest = location;
	if (r <= NUM && heap[r] > heap[largest])
	{
		largest = r;
	}
	if (location != largest)
	{
		temp = heap[location];
		heap[location] = heap[largest];
		heap[largest] = temp;
		max_heapify(heap, largest);
	}
}

void bulid_max_heap(int heap[])
{
	//叶子节点不用max_heapify,所以是节点数的一半
	for (int i = NUM / 2; i >= 1; i--)
	{
		max_heapify(heap, i);
	}
}

int main()
{
	int heap[NUM + 1] = {0};
	srand(time(NULL));
	for (int i = 1; i <= NUM; i++)
	{
		heap[i] = rand() % 100;
	}
	print(heap, NUM);

	bulid_max_heap(heap);
	cout << "-------------" << endl;
	print(heap, NUM);
	return 0;
}


结果如下:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值