java 堆排序代码(最小堆)


package com.juxuny.heap;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Juxuny on 2015/2/10.
 */
public class Heap {

    private int MAX = 2 << 20;
    private Node[] arr;
    private int size = 0;


    public Heap() {
        arr = new Node[MAX];
    }

    public int add(Node n) {
        if (size == 0 ) {
            arr[size ++] = n;
            return 0;
        }
        if (size >= MAX) return -1;
        Node tmp ;
        arr[size ++] = n;
        int j = size - 1;
        for (int i = (size -1) >> 1; i >= 0 ; i = (i - 1 ) >> 1) {
            if (arr[j].compare(arr[i])) {
                tmp = arr[j];
                arr[j] = arr[i];
                arr[i] = tmp;
            }
            j = i;
        }
        return 0;
    }

    public Node pop() {
        Node ret = null;
        if (size == 0 ) return ret;
        ret = arr[0];
        Node tmp = arr[--size];
        int i = 0;
        for (i = 0 ; i < size >> 1; ) {
            int child = i << 1 | 1;
            int right = child + 1;
            if (right < size && arr[right].compare(arr[child])) child = right;
            if (tmp.compare(arr[child])) break;
            arr[i] = arr[child];
            i = child;
        }
        arr[i] = tmp;
        return ret;
    }

    public Node top() {
        if (size == 0 ) return null;
        return arr[0];
    }
}


import com.juxuny.heap.Heap;
import com.juxuny.heap.Node;

import java.util.Random;

/**
 * Created by Juxuny on 2015/2/10.
 */
public class Main {
    public static void main(String[] args) {
        Random random = new Random();
        Heap heap = new Heap();
        for (int i = 0 ; i < 1000; i ++ ) {
            heap.add(new MinNode(random.nextInt(10000)));
        }
        MinNode minNode = (MinNode) heap.pop();
        while (minNode != null ) {
            System.out.printf("%d ", minNode.time);
            minNode = (MinNode) heap.pop();
        }
    }

    public  static class MinNode extends Node {

        public long time;

        public MinNode(long time) {
            this.time = time;
        }

        @Override
        public boolean compare(Node n) {
            return time < ((MinNode)n).time;
        }
    }
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值