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;
}
}
}