import java.util.Arrays;
public class Test {
public int[] elem;
public int usedSize;
public Test() {
this.elem = new int[10];
}
/**
* 填充数据
* @param array
*/
public void initElem(int[] array) {
for(int i = 0;i < array.length;i++) {
elem[i] = array[i];
usedSize++;
}
}
public void createBigHeap() {
for(int parent = (usedSize-1-1)/2;parent >= 0;parent--) {
shiftDown(parent,usedSize);
}
}
/**
* 向下调整
* @param
* @param parent
*/
public void shiftDown(int parent,int end) {
int child = 2*parent + 1;
while(child < end) {
//如果右孩子存在,找到左右孩子中较小的孩子,用child进行标记
if(child+1 < usedSize && elem[child] < elem[child+1]) {
child++;
}
//child一定是 左右孩子最大值的下标
if(elem[child] > elem[parent]) {
//交换
swap(child,parent);
parent = child;
child = 2*parent+1;
}else {
break;
}
}
}
private void swap(int i,int j) {
int tmp = elem[i];
elem[i] = elem[j];
elem[j] = tmp;
}
public int poll() {
int tmp = elem[0];//删除嘴高的那个值
swap(0,usedSize-1);
usedSize--;
shiftDown(0,usedSize);
return tmp;
}
public void offer(int val) {
//1.判断满
if(isFull()) {
//扩容
this.elem = Arrays.copyOf(elem,2*elem.length);
}
//2.插入元素
elem[usedSize] = val;
usedSize++;
//3.开始向上调整
siftUp(usedSize-1);
}
private void siftUp(int child) {
int parent = (child-1) / 2;
while(child > 0) {
if(elem[child] > elem[parent]) {
swap(child,parent);
child = parent;
parent = (child-1)/2;
}else {
break;
}
}
}
public boolean isFull() {
return usedSize == elem.length;
}
public void heapSort() {
int end = usedSize-1;
while(end > 0) {
swap(0,end);
shiftDown(0,end-1);
end--;
}
}
}
优先级队列(堆)的模拟实现
最新推荐文章于 2024-07-23 12:29:02 发布