堆和堆排序, update@20210105
最大堆(max heap)的实现
import java.util.ArrayList;
import java.util.concurrent.ThreadLocalRandom;
/**
* max heap
*
* @author fangchao
*/
public class Heap {
private ArrayList<Integer> list = new ArrayList<>();
public Heap() {
list.add(null);
}
public void print() {
System.out.println(list.toString());
}
public void add(Integer integer) {
list.add(integer);
int index = list.size() - 1;
heapIt(index);
}
private void heapIt(int index) {
int parent;
while ((parent = index / 2) > 0) {
int p = list.get(parent);
int c = list.get(index);
if (p < c) {
list.set(parent, c);
list.set(index, p);
index = parent;
} else {
break;
}
}
}
public static void main(String[] args) {
int size = 15;
int min = 1;
int max = 10;
int testNum = 100;
for (int j = 0; j < testNum; j++) {
Heap heap = new Heap();
for (int i = 0; i < size; i++) {
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
heap.add(randomNum);
}
heap.print();
}
}
}