用堆实现数组的排序 (从小到大)

用堆实现数组的排序 (从小到大)

//代码:
#include
#include <Windows.h>

using namespace std;

#define MAX_SIZE 10

//堆排序
typedef struct _Heap {
int *arr; //首地址
int size; //元素个数
int capacity; //元素容量
}_Heap;

//整理堆
static void adjustDown(_Heap *p_heap,int index) {
if (!p_heap) {
return;
}

int tmp = p_heap->arr[index];

int parent, child;

for (parent = index; parent * 2 + 1 < p_heap->size; parent = child) {
	child = parent * 2 + 1;

	if (child + 1 < p_heap->size && p_heap->arr[child + 1] > p_heap->arr[child]) {
		child = child + 1;
	}
	
	//子节点的最大的节点的值大于父节点的值
	if (p_heap->arr[child] > tmp) {
		p_heap->arr[parent] = p_heap->arr[child];
		p_heap->arr[child] = tmp;
	}
	else {
		break;
	}	
}

}

//建堆
static void buildHeap(_Heap *p_heap) {
if (!p_heap) {
return;
}

for (int i = (p_heap->size - 1 - 1) / 2; i >= 0; i--) {
	adjustDown(p_heap, i);
}	

}

//进行最大值排序
bool popMax(_Heap *p_heap) {
if (!p_heap) {
return false;
}

while (p_heap->size > 0) {
	int tmp = p_heap->arr[0];
	p_heap->arr[0] = p_heap->arr[p_heap->size - 1];
	p_heap->arr[p_heap->size - 1] = tmp;
	p_heap->size--; 

	//首节点
	adjustDown(p_heap, 0);
}


return true;

}

//初始化
bool heapInit(_Heap *p_heap, int *p_data) {
if (!p_heap || !p_data) {
return false;
}

p_heap->arr = p_data;
if (!p_heap) {
	return false;
}

//容量
p_heap->capacity = MAX_SIZE;
p_heap->size = MAX_SIZE;

//建堆
buildHeap(p_heap);


return true;

}

int main(void) {
_Heap heap;

int data[MAX_SIZE] = { 18,20,45,13,52,19,53,44,37,22 };

if (!(heapInit(&heap, data))) {
	fprintf(stderr, "建堆失败!\n");
	exit(-1);
}

//排序
if (!(popMax(&heap))) {
	fprintf(stderr, "进行堆排序失败!\n");
	exit(-1);
}

for (int i = 0; i < MAX_SIZE; i++) {
	cout << data[i] << ' ';
}




system("pause");

return 0;

}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘉人、LiangYing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值