//数组中有效元素的长度
private int heapSize = -1;
//存储元素的堆
private int[] heap;
/**
* 堆结构的实现类
* 大根堆
*/
//往大根堆中插入一个元素
public void push(int value) {
//直接将当前值存入一个数组中,然后用heapInsert()将其挂载在大根堆(完全二叉树)上
heap[heapSize] = value;
heapInsert(heap, heapSize);
//插入一个值后,让有效元素值加一
heapSize++;
}
//参数:数组 有效元素长度(即当前元素的索引位置)
public void heapInsert(int[] arr, int heapSize) {
//获取当前结点的父结点
int index = (heapSize - 1) >> 1;
//循环判断 如果新进来的值比自己的父结点要大,让交换他和父结点,
while (arr[heapSize] > arr[index]) {
swap(arr, heapSize, index);
//再次获取交换后当前结点的父结点
index = (heapSize - 1) >> 1;
}
}
//返回堆中的根结点,并将其移除
/*
思路:先直接将最后一个元素和根结点进行交换,然后对新的根结点进行heapify,将其和左右孩子进行比较,或不动,或下移
*/
p
堆结构(大根堆为例,java实现)
最新推荐文章于 2024-05-11 12:00:46 发布