Java数据结构--堆以及堆排序
程序员文章站
2022-06-03 08:23:23
...
Java数据结构–堆以及堆排序
堆(Heap)是计算机科学中一类特殊的数据结构的统称。堆通常是一个可以被看做一棵完全二叉树的数组对象。
堆类
public class Heap<T extends Comparable<T>> {
private T[] items;
private int N;
public Heap(int capacity) {
this.items = (T[]) new Comparable[capacity+1];
this.N = 0;
}
private boolean less(int i, int j) {
return items[i].compareTo(items[j]) < 0;
}
private void exch(int i, int j) {
T temp = items[i];
items[i] = items[j];
items[j] = temp;
}
public void insert(T t) {
items[++N] = t;
swim(N);
}
public void swim(int k) {
while (k > 1) {
if (less(k / 2, k)) {
exch(k / 2, k);
}
k = k / 2;
}
}
public T delMax() {
T max = items[1];
exch(1,N);
items[N] = null;
N--;
sink(1);
return max;
}
private void sink(int k) {
while (2*k<=N) {
int max;
if(2*k+1<=N){
if(less(2*k,2*k+1)){
max=2*k+1;
}else {
max = 2 * k;
}
}
else{
max=2*k;
}
if(!less(k,max)){
break;
}
exch(k,max);
k=max;
}
}
}
测试类
public class HeapTest {
public static void main(String[] args) {
Heap<String> heap=new Heap<>(10);
heap.insert("A");
heap.insert("B");
heap.insert("C");
heap.insert("D");
heap.insert("E");
heap.insert("F");
heap.insert("G");
String result=null;
while((result=heap.delMax())!=null){
System.out.print(result+" ");
}
}
}