Skip to content

Instantly share code, notes, and snippets.

@theahmadzai
Created June 10, 2019 19:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theahmadzai/3b8b3e7a6471dc242e2e4476b8ca5558 to your computer and use it in GitHub Desktop.
Save theahmadzai/3b8b3e7a6471dc242e2e4476b8ca5558 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
class MinHeap {
private int capacity = 10;
private int size = 0;
int[] items = new int[capacity];
private int getLeftChildIndex(int parentIndex) {
return 2 * parentIndex + 1;
}
private int getRightChildIndex(int parentIndex) {
return 2 * parentIndex + 2;
}
private int getParentIndex(int childIndex) {
return (childIndex - 1) / 2;
}
private boolean hasLeftChild(int index) {
return getLeftChildIndex(index) < size;
}
private boolean hasRightChild(int index) {
return getRightChildIndex(index) < size;
}
private boolean hasParent(int index) {
return getParentIndex(index) >= 0;
}
private int leftChild(int index) {
return items[getLeftChildIndex(index)];
}
private int rightChild(int index) {
return items[getRightChildIndex(index)];
}
private int parent(int index) {
return items[getParentIndex(index)];
}
private void swap(int indexOne, int indexTwo) {
int temp = items[indexOne];
items[indexOne] = items[indexTwo];
items[indexTwo] = temp;
}
private void ensureExtraCapacity() {
if(size == capacity) {
items = Arrays.copyOf(items, capacity * 2);
capacity *= 2;
}
}
public int peek() {
if(size == 0) throw new IllegalStateException();
return items[0];
}
public int poll() {
if(size == 0) throw new IllegalStateException();
int item = items[0];
items[0] = items[size-1];
size--;
heapifyDown();
return item;
}
public void add(int item) {
ensureExtraCapacity();
items[size] = item;
size++;
heapifyUp();
}
public void heapifyUp() {
int index = size - 1;
while(hasParent(index) && parent(index) > items[index]) {
int parent = getParentIndex(index);
swap(parent, index);
index = parent;
}
}
public void heapifyDown() {
int index = 0;
while(hasLeftChild(index)) {
int smallerChildIndex = getLeftChildIndex(index);
if(hasLeftChild(index) && (rightChild(index) < leftChild(index))) {
smallerChildIndex = getRightChildIndex(index);
}
if(items[index] < items[smallerChildIndex]) {
break;
} else {
swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
public void print() {
for(int i : items) {
System.out.print(i + ", ");
}
}
}
public class Test
{
public static void main(String[] args)
{
MinHeap heap = new MinHeap();
heap.add(3);
heap.add(5);
heap.add(6);
heap.add(2);
heap.add(1);
heap.add(4);
heap.add(0);
heap.add(0);
heap.add(10);
heap.add(2);
heap.print();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment