堆排序

#include <iostream>
using namespace std;
void print_array(int* array, int size);
void build_heap(int* array, int size);
void swap(int& a, int& b);
void heapify(int* array, int node, int size);
void heap_sort(int* array, int size);


void main()
{
	int* array;
	int size;


	cin >> size;
	array = new int[size];


	for (int i=0; i<size; i++)
		array[i] = rand()%100;


	print_array(array, size);
	build_heap(array, size);
	print_array(array, size);
	heap_sort(array, size);
	print_array(array, size);
}


void print_array(int* array, int size)
{
	for (int i=0; i<size;  i++)
		cout << array[i] << " ";


	cout << endl;
}


// build a heap
void build_heap(int* array, int size)
{
	int parent = size / 2 - 1;
	for(parent = size / 2 - 1; parent >=0; parent--)
	{
		heapify(array, parent, size);
	}
}


void swap(int& a, int& b)
{
	int t = a;
	a = b;
	b = t;
}


// make a parent node's value greater than its children
void heapify(int* array, int node, int size)
{
	// is it a leaf?
	if (node > size / 2 - 1)
		return ;


	int left_child = node * 2 + 1;
	int right_child = left_child + 1;
	
	int max = node;
	if (left_child < size && array[left_child] > array[max])
		max = left_child;


	if (right_child < size && array[right_child] > array[max])
		max = right_child;


	// if exchanged, it may affects the 'heap attribute' of its children
	if (max != node)
	{
		swap(array[node], array[max]);
		heapify(array, max, size);
	}
}


// sort. first, build a heap, than, extract the top node.
void heap_sort(int* array, int size)
{
	build_heap(array, size);


	for (int i=size-1; i>0; i--)
	{
		swap(array[i], array[0]);
		heapify(array, 0, i);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值