堆(完全二叉树的一种) 模拟

堆 模拟

#include 
#include 

typedef int HeapDataType;
typedef struct Heap
{
	HeapDataType* data;
	int size;
	int capacity;
}heap;

#define INIT_CAPACITY 5
void HeapInit(heap* php)
{
	assert(php);
	php->size = 0;
	php->capacity = INIT_CAPACITY;
	php->data = (HeapDataType*)malloc(sizeof(HeapDataType) * (php->capacity));
}

void swap(HeapDataType* p1, HeapDataType* p2)
{
	HeapDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

//堆的向上调整
void AdjustUp(HeapDataType* p, int child)
{
	assert(p);
	int parent = (child - 1) / 2;
	while (child > 0)
	{
		if (p[child] > p[parent])
		{
			swap(p + child, p + parent);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

//堆的向下调整
void AdjustDown(HeapDataType* p, int parent, int n)
{
	assert(p);
	int child = 2 * parent + 1;
	while (child < n)
	{
		if (child + 1 < n && p[child + 1] > p[child])
		{
			child++;
		}
		if (p[child] > p[parent])
		{
			swap(p + child, p + parent);
			parent = child;
			child = 2 * parent + 1;
		}
		else
		{
			break;
		}
	}
}

//判断是否为空
bool HeapEmpty(heap* php)
{
	assert(php);
	return php->size == 0;
}

//堆中插入一个数据
void HeapPush(heap * php, int x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		HeapDataType* tmp = (HeapDataType*)realloc(php->data, sizeof(HeapDataType) * (php->capacity * 2));
		if (tmp == NULL)
		{
			return;
		}
		php->data = tmp;
		php->capacity *= 2;
	}
	php->data[php->size] = x;
	php->size++;
	AdjustUp(php->data, php->size - 1);
}

//堆中弹出一个数据(当然是堆顶,这样才有意义)
void HeapPop(heap* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	swap(php->data, php->data + php->size - 1);
	php->size--;
	AdjustDown(php->data, 0, php->size);
}

//堆顶数据(最值)
int HeapTop(heap* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	return php->data[0];
}

//自上而下建堆
void CreateHeapFromUp(HeapDataType* ptr, int size)
{
	for (int i = 1; i < size; i++)
	{
		AdjustUp(ptr, i);
	}
}

//自下而上建堆
void CreateHeapFromDown(HeapDataType* ptr, int size)
{
	for (int i = (size - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(ptr, i, size);
	}
}

//堆排序
void HeapSort(int* arr, int size)
{
	//建堆
	for (int i = (size - 1 - 1) / 2; i >= 0; i--)
	{
		AdjustDown(arr, i, size);
	}
	//调堆
	int end = size - 1;
	while (end != 0)
	{
		int tmp = arr[0];
		arr[0] = arr[end];
		arr[end] = tmp;
		AdjustDown(arr, 0, end);
		end--;
	}
}

你可能感兴趣的:(DS,数据结构)