PercolateUp()
When to use?
The element need to be moved up to maintain the heap's property, for example, when offering a new element into the heap.
How?
Compare the element with it's parent, move it up when necessary. Do this until the element does not need to be moved.
PercolateDown()
When to use?
The element need to be moved down to maintain the heap's property, for example, when poll the root element from the heap
How?
Compare the element with it's two children, swap the element with the child with the right property of heap. Do this until the element does not need to be moved.
Heapify()
convert an array into a heap in O(n)
How?
For each node that has at least one child, we perform percolateDown()
Update()
How?
Either you need to percolateUp() or percolateDown() on that element
If you need to find the position of the element first, takes O(n)
Implementation of Capacity Limited Min Heap
public class ImplementMinHeap {
public class MinHeap{
private int[] arr;
private int size;
public MinHeap(int[] arr){
if(arr == null || arr.length == 0) throw new IllegalArgumentException("input array cannot be null or empty");
this.arr = arr;
size = arr.length;
heapify();
}
private void heapify(){
for(int i = size/2 - 1; i >= 0; i--){
percolateDown(i);
}
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
private void percolateDown(int index){
while(index <= (size/2 - 1)){
int leftChildIndex = index*2 + 1;
int rightChildIndex = index*2 + 2;
int swapCandidate = leftChildIndex;
if(rightChildIndex < size - 1 && arr[rightChildIndex] < arr[leftChildIndex]){
swapCandidate = rightChildIndex;
}
if(arr[index] > arr[swapCandidate]) swap(arr, swapCandidate, index);
else break;
index = swapCandidate;
}
}
private void percolateUp(int index){
//if it has parent
while(index > 0){
int parentIndex = (index - 1)/2;
if(arr[parentIndex] > arr[index]){
swap(arr, parentIndex, index);
}else break;
index = parentIndex;
}
}
private void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = temp;
temp = arr[j];
}
public int peek(){
if(size == 0) return -1;
return arr[0];
}
public int poll(){
if(size == 0) throw new NoSuchElementException("heap is empty");
int res = arr[0];
arr[0] = arr[size - 1];
size--;
percolateDown(0);
return res;
}
public void offer(int ele){
size++;
arr[size - 1] = ele;
percolateUp(size - 1);
}
public int update(int index, int ele){
if(index < 0 || index > size - 1){
throw new ArrayIndexOutOfBoundsException("invalid index");
}
int res = arr[index];
arr[index] = ele;
if(res > ele){
percolateUp(index);
}else percolateDown(index);
return res;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。