C++は大きい根の山を創立することを実現します

899 ワード

#include 
using namespace std;

void swap(int *a, int *b)
{
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

void adjust_heap(int *Array, int index, int len)
{
	int cur = index;
	int right_child = 2 * (cur + 1);
		
	while(right_child < len)
	{
		if(Array[right_child] < Array[right_child-1])
		{
			right_child--;
		}
		swap(Array[cur], Array[right_child]);
		cur = right_child;
		right_child = 2 * (cur + 1);
	}

	if(right_child == len)
	{
		if(Array[len] > Array[right_child])
		{
			swap(Array[right_child], Array[len]);	
		}	
	}
}

void make_heap(int *Array, int len)
{
	int index = (len - 2)/2;
	do{	
		adjust_heap(Array, index, len);
		index--;
	}while(index != -1);
	
}
int main()
{
	const int len = 9;
	int array[len] = {1,2,3,4,5,6,7,8,9};
	make_heap(array, len);
	
	for(int i = 0; i < len ; i++)
	{
		cout<