堆排序模拟

 


import java.io.*;


public class Main{
    static int N = 100010;
    static int[] h = new int[N];
    static int size;
    public static void swap(int x,int y){
        int temp = h[x];
        h[x] = h[y];
        h[y] = temp;
    }

    public static void down(int u){
        //t是三个中最小值的下标
        int t = u;
        if (u * 2 <= size && h[u * 2] < h[t]) t = 2 * u;
        if (u * 2 + 1 <= size && h[u * 2 + 1] < h [t]) t = 2 * u + 1;
        if (t != u){
            swap(u,t);
            down(t);
        }
    }
    static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));

    public static void main(String[] args) throws IOException{
        String[] init = in.readLine().split(" ");
        int n = Integer.parseInt(init[0]);  //n个数
        int m = Integer.parseInt(init[1]);  //找m个最小的数
        init = in.readLine().split(" ");
        for (int i = 1; i <= n; i++) {
            h[i] = Integer.parseInt(init[i - 1]);
        }
        size = n;
        
        //建堆,小顶堆:所有的非叶子节点都得是他与他孩子的最小节点
        //n是最后一个节点,它的父亲是n/2,即最后一个非叶子节点
        //把该节点以前的所有节点都down,就可以达到建堆的目的
        for (int i = n / 2; i > 0; i--) {
            down(i);
        }
        while (m-->0){
            out.write(h[1] + " ");
            h[1] = h[size--];
            down(size);
        }
        in.close();
        out.flush();
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值