Java堆排序

PriorityQueue

public class PriorityQueueMain {

    public static void main(String[] args) {
        int[] temp = {40, 2, 33, 26, 35, 8, 8, 26, 29, 2};
        PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
        for (int i = 0; i < temp.length; i++) {
            priorityQueue.offer(temp[i]);
        }
        while (!priorityQueue.isEmpty()) {
            System.out.format("%d ", priorityQueue.poll());
        }
    }
}

自己实现

详细原理,只是在push的时候他写错了

public class ArraySmallHeap {
    public static void main(String[] args) {
        int[] temp = {40, 2, 33, 26, 35, 8, 8, 26, 29, 2};
        heap = new int[temp.length];
        for (int j : temp) {
            push(j);
        }
        for (int i = 0; i < temp.length; i++) {
            System.out.format("%d ", pop());
        }
    }


    private static int[] heap;

    private static int size;

    private static void down(int k) {
        int t = k;
        int l = k << 1, r = (k << 1) + 1;
        if (l <= size && heap[t] > heap[l]) {
            t = l;
        }

        if (r <= size && heap[t] > heap[r]) {
            t = r;
        }

        if (t != k) {
            int temp = heap[k];
            heap[k] = heap[t];
            heap[t] = temp;
            down(t);
        }
    }

    private static void up(int k) {
        int u = k / 2;
        if (u >= 1 && heap[k] < heap[u]) {
            int temp = heap[k];
            heap[k] = heap[u];
            heap[u] = temp;
            up(u);
        }
    }

    public static void push(int v) {
        heap[++size] = v;
        up(size);
    }

    public static int pop() {
        int v = heap[1];
        heap[1] = heap[size--];
        down(1);
        return v;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值