min-priority queue


根据算法导论章节实现。

#include "2.h"
#include 

int g_heapsize;
int g_length;

void min_heap_heapify(int *data, int i)
{
	int left = 2 * i;
	int right = 2 * i + 1;

	int min;
	if(left <= g_heapsize && data[left] < data[i])
	{
		min = left;
	}
	else
	{
		min = i;
	}

	if(right <= g_heapsize && data[right] < data[min])
	{
		min = right;
	}

	if(min != i)
	{
		int tmp = data[i];
		data[i] = data[min];
		data[min] = tmp;
		min_heap_heapify(data, min);
	}
}

void min_heap_init_length(int length)
{
	g_length = length;
}

void min_heap_build(int *data)
{
	g_heapsize = g_length;
	int i;
	for(i = g_length / 2; i > 0; i--)
	{
		min_heap_heapify(data, i);
	}
}

void min_heap_decrease_key(int *data, int i, int key)
{
	if( key > data[i])
	{
		printf("key should not be larger than data[%d]\n", i);
		return;
	}

	data[i] = key;
	int parent = i / 2;
	while( i > 1 && data[parent] > key)
	{
		int tmp = data[i];
		data[i] = data[parent];
		data[parent] = tmp;

		i = parent;
		parent = i / 2;
	}
}

void min_heap_insert(int *data, int key)
{
	g_heapsize = g_heapsize + 1;
	data[g_heapsize] = 1 << 31 - 1;
	min_heap_decrease_key(data, g_heapsize, key); 
}

int min_heap_extract(int *data)
{
	min_heap_build(data);
	int min = data[1];
	data[1] = data[g_heapsize];
	g_heapsize = g_heapsize -1;
	min_heap_heapify(data, 1);
	return data[1];
}


int main(int argc, char **argv)
{
	int data[] = {-1, 234, 23, 15, 67, 5, 88, 100, 50};
	min_heap_init_length(sizeof(data)/sizeof(data[0])-1);
	int min = min_heap_extract(data);
	min_heap_insert(data, 4);
	return 0;
}


你可能感兴趣的:(Algorithms)