Created
May 28, 2018 16:12
-
-
Save zeroFruit/ce9abe5a09278ba3ee83d2ab8f59da57 to your computer and use it in GitHub Desktop.
Min Heap using Generic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* referenced | |
* 1. http://www.techiedelight.com/min-heap-max-heap-implementation-in-java/ | |
* 2. https://gist.github.com/flexelem/70b120ac9bf2965f419f | |
* */ | |
class MinHeap<E extends Comparable<E>> { | |
private ArrayList<E> heap; | |
MinHeap() { | |
heap = new ArrayList<>(); | |
} | |
public void insert(E item) { | |
heap.add(item); | |
int i = heap.size() - 1; | |
int parent = parent(i); | |
while (parent != i && heap.get(i).compareTo(heap.get(parent)) < 0) { | |
swap(i, parent); | |
i = parent; | |
parent = parent(i); | |
} | |
} | |
public E remove() { | |
E root; | |
if (size() == 0) | |
return null; | |
if (size() == 1) { | |
root = heap.remove(0); | |
return root; | |
} | |
root = heap.get(0); | |
E lastItem = heap.remove(size() - 1); | |
heap.set(0, lastItem); | |
heapifyDown(0); | |
return root; | |
} | |
private void heapifyDown(int i) { | |
int left = left(i); | |
int right = right(i); | |
int smallest = i; | |
if (left < size() && heap.get(left).compareTo(heap.get(i)) < 0) { | |
smallest = left; | |
} | |
if (right < size() && heap.get(right).compareTo(heap.get(smallest)) < 0) { | |
smallest = right; | |
} | |
if (smallest != i) { | |
swap(i, smallest); | |
heapifyDown(smallest); | |
} | |
} | |
public void print() { | |
for (int i = 0; i < heap.size(); i++) { | |
/* print */ | |
} | |
} | |
public boolean validate() { | |
for (int i = 1; i < heap.size(); i++) { | |
if (heap.get(i).compareTo(heap.get(parent(i))) < 0) { | |
print(); | |
return false; | |
} | |
} | |
print(); | |
return true; | |
} | |
public int size() { | |
return heap.size(); | |
} | |
public void clear() { | |
heap.clear(); | |
} | |
private int parent(int i) { | |
if (i == 0) { /* if i is already a root node */ | |
return 0; | |
} | |
return (i - 1) / 2; | |
} | |
private int left(int i) { | |
return (2 * i + 1); | |
} | |
private int right(int i) { | |
return (2 * i + 2); | |
} | |
private void swap(int i, int parent) { | |
E tmp = heap.get(parent); | |
heap.set(parent, heap.get(i)); | |
heap.set(i, tmp); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment