堆排序(小根堆)

输入一个长度为 nn 的整数数列,从小到大输出前 mm 小的数。

输入格式

第一行包含整数 nn 和 mm。

第二行包含 nn 个整数,表示整数数列。

输出格式

共一行,包含 mm 个整数,表示整数数列中前 mm 小的数。

数据范围

1≤m≤n≤1051≤m≤n≤105,
1≤数列中元素≤1091≤数列中元素≤109

输入样例:

5 3
4 5 1 3 2

输出样例:

1 2 3

 

 

C++

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e5+1;
int h[N],size;
void down(int x)
{
	int t = x;
	if(x*2<=size && h[x*2]<h[t]) t = x*2;
	if(x*2+1<=size && h[x*2+1]<h[t]) t = x*2+1;
	if(t!=x){
		swap(h[t],h[x]);
		down(t);
	}	
} 
int main()
{
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=n;i++) cin>>h[i];
	size = n;
	for(int i=n/2;i!=0;i--) down(i);
	while(m--){
		cout<<h[1]<<' ';
		h[1] = h[size--];
		down(1);
	}
	return 0;
}

 python

N = 100001
h = [0] * N
size = 0
def down(x):
    global h, size
    t = x
    if x * 2 <= size and h[x * 2] < h[t]:
        t = x * 2
    if x * 2 + 1 <= size and h[x * 2 + 1] < h[t]:
        t = x * 2 + 1
    if t != x:
        temp = h[t]
        h[t] = h[x]
        h[x] = temp
        down(t)
def main():
    global h, size
    n, m = map(int, input().split(" "))
    h = list(map(int, input().split(" ")))
    h.insert(0, 0) #因为堆要从数组下标为1开始,所以必须要在下标为0的位置插入一个数,让所有数整体后移一位
    size = n
    i = int(n / 2)
    while i != 0:
        down(i)
        i -= 1
    for i in range(m):
        print(h[1], end=" ")
        h[1] = h[size]
        size -= 1
        down(1)
main()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

天行九歌。

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

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

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

打赏作者

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

抵扣说明:

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

余额充值