堆排序 ← 改编自《啊哈!算法》

【算法分析】
● 堆排序依托于完全二叉树的结构,需要解决如下两个问题:
建初堆:如何将一个无序序列建成一个堆?
调整堆:去掉堆顶元素,在堆顶元素改变之后,如何调整剩余元素成为一个新的堆?


● “筛选法”对无序序列构建大根堆的算法步骤:
构建包含n个数的无序序列对应的完全二叉树;
依序遍历第i =
n/2 ~ 1个结点,若第2i、2i+1个结点中的较大值,比第i个结点的值大,交换。

● 堆排序算法步骤:
首先,对无序序列建初堆;
其次,在初始堆的基础上,反复交换堆顶元素和最后一个元素,然后重新调整堆,直至最后得到一个有序序列。

【算法代码】

#include<bits/stdc++.h>
using namespace std;

const int maxn=1005;
int h[maxn]; //save heap
int n;

void swap(int a,int b) {
	int t=h[a];
	h[a]=h[b];
	h[b]=t;
}

void siftdown(int i) {
	int t,flag=0;
	while(i<=n/2 && flag==0) {
		if(h[i]<h[i*2]) t=i*2;
		else t=i;

		if(i*2+1<=n) { //if has right child
			if(h[t]<h[i*2+1]) t=i*2+1;
		}

		if(t!=i) {
			swap(t,i);
			i=t;
		} else flag=1;
	}
}

void creat() {//create heap
	for(int i=n/2; i>=1; i--) siftdown(i);
}

void heapsort() {
	while(n>1) {
		swap(1,n);
		n--;
		siftdown(1);
	}
}

int main() {
	int tot;
	cin>>tot;
	for(int i=1; i<=tot; i++) cin>>h[i];
	
	n=tot;
	creat();
	heapsort();
	
	for(int i=1; i<=tot; i++) cout<<h[i]<<" ";
	
	return 0;
}

/*
in:
12
66 6 36 7 22 17 12 2 19 25 28 1

out:
1 2 6 7 12 17 19 22 25 28 36 66
*/



【参考文献】
https://blog.51cto.com/ahalei
https://blog.51cto.com/ahalei/1425314
https://blog.51cto.com/ahalei/1427156
https://blog.csdn.net/hnjzsyjyj/article/details/127840651

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值