数据结构--堆排序

堆排序:
通过堆的特点,先将头结点(即最大值的节点)与最后一个节点交换,堆大小-1,那么最大值就在最后,之后的操作也不会干扰到他,在把交换上去的节点,进行调整,使堆恢复正常,重复操作。

#include<iostream>
#include<Windows.h>
#define MAX_LENGTH 100
using namespace std;
typedef struct Heap {
	int* arr;
	int size;
	int max_length;
}Heap;
bool init(Heap& heap, int* arry, int size);
bool popMAX(Heap& heap, int& value);
void Build_Heap(Heap& heap);
void adjustDown(Heap& heap, int index);
void Heap_sort(Heap& heap);
int main() {
	Heap heap;
	int arry[] = { 1, 2, 3, 87, 93, 82, 92, 86, 95 };
	//堆的初始化
	if (!init(heap, arry, sizeof(arry) / sizeof(arry[0]))) {
		cout << "初始化失败" << endl;
	}
	for (int i = 0; i < heap.size; i++) {
		printf("the %dth element:%d\n", i, heap.arr[i]);
	}
	Heap_sort(heap);
	for (int i = 0; i < heap.max_length; i++) {
		printf("%d\n",heap.arr[i]);
	}
	system("pause");
	return 0;
}
bool init(Heap& heap, int* arry, int size) {
	heap.size = heap.max_length = size;
	heap.arr = arry;
	Build_Heap(heap);
	return true;
}
void Build_Heap(Heap& heap) {
	for (int i = (heap.size / 2) - 1;i >= 0;i--) {
		adjustDown(heap, i);
	}
}
void adjustDown(Heap& heap, int index) {
	int tmp = heap.arr[index];
	int child, parent;
	for (parent = index;parent * 2 + 1 < heap.size;parent = child) {
		child = parent * 2 + 1;
		if ((child + 1) < heap.size && heap.arr[child] < heap.arr[child + 1]) {
			child++;
		}
		if (tmp < heap.arr[child]) {
			heap.arr[parent] = heap.arr[child];
			heap.arr[child] = tmp;
		}
		else {
			break;
		}
	}
}
bool popMAX(Heap& heap, int& value) {
	if (heap.size == 0) {
		cout << "堆为空" << endl;
		return false;
	}
	value = heap.arr[0];
	heap.arr[0] = heap.arr[--heap.size];
	adjustDown(heap, 0);
	return true;
}
void Heap_sort(Heap& heap) {

	while (heap.size) {
		int tmp = heap.arr[0];
		heap.arr[0] = heap.arr[heap.size - 1];
		heap.arr[heap.size - 1] = tmp;
		heap.size--;
		adjustDown(heap, 0);
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值