代码主要是看算法书结合自己理解实现
public class MaxPQ<T extends Comparable> {
private Entity[] data;
private int n;
public MaxPQ(int n){
this.data = new Entity[n + 1];
}
public boolean isEmpty(){
return n == 0;
}
public int size(){
return n;
}
public void insert(Entity entity){
if (entity == null){
return;
}
int index = ++n;
if (index < data.length){
data[index] = entity;
up(index);
}
}
public Entity delMax(){
Entity max = data[1];
data[1] = data[n];
data[n] = null;
n--;
down(1);
return max;
}
private boolean compare(Entity entity,Entity entity1){
if (entity == null || entity1 == null){
return false;
}
return entity.compareTo(entity1) > 0;
}
private void change(int entity,int entity1){
Entity temp = data[entity];
data[entity] = data[entity1];
data[entity1] = temp;
}
private void up(int index) {
int parent = 0;
while ((parent = index / 2) >= 1) {
if (compare(data[index], data[parent])) {
change(index, parent);
}
index /= 2;
}
}
private void down(int index) {
while (2 * index <= n) {
int max = 0;
if (data[2 * index + 1] == null){
max = 2 * index;
}else {
if (compare(data[2 * index], data[2 * index + 1])) {
max = 2 * index;
} else {
max = 2 * index + 1;
}
}
if (data[max] != null) {
if (compare(data[max], data[index])) {
change(max, index);
}
}
index = max;
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
Random random = new Random();
Entity[] entitys = new Entity[60000000];
MaxPQ maxPQ = new MaxPQ(60000000);
for (int i = 0;i < 60000000;++i){
Entity entity = new Entity(random.nextInt(600000000));
maxPQ.insert(entity);
}
int j = 0;
while (j < 60000000){
entitys[j] = maxPQ.delMax();
j++;
}
long end = System.currentTimeMillis();
System.out.println("Quicksort :"+(end - start) / 1000);
assert SortUtil.isSortedDes(entitys);
}
}
注:
(1)可以基于此代码 实现堆排序
(2)实现查找TopN数据
(3)查找第k小的数据 …