/Heap.java Secret
Created
May 2, 2018 01:01
Heap
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
import java.util.ArrayList; | |
public class Heap { | |
private ArrayList<Integer> arr; | |
public Heap() { | |
arr = new ArrayList<>(); | |
} | |
public Heap(int... values) { | |
this(); | |
for (int v : values) { | |
insert(v); | |
} | |
} | |
private void heapUp(int index) { | |
int parentIdx = (index - 1) / 2; | |
if (arr.get(index) > arr.get(parentIdx)) { | |
int temp = arr.get(index); | |
arr.set(index, arr.get(parentIdx)); | |
arr.set(parentIdx, temp); | |
heapUp(parentIdx); | |
} | |
} | |
private void heapDown(int index) { | |
int leftChildIndex = index * 2 + 1; | |
int rightChildIndex = index * 2 + 2; | |
int largerValueIndex = index; | |
if (leftChildIndex < arr.size() && arr.get(leftChildIndex) > arr.get(largerValueIndex)) { | |
largerValueIndex = leftChildIndex; | |
} | |
if (rightChildIndex < arr.size() && arr.get(rightChildIndex) > arr.get(largerValueIndex)) { | |
largerValueIndex = rightChildIndex; | |
} | |
if (largerValueIndex != index) { | |
int temp = arr.get(largerValueIndex); | |
arr.set(largerValueIndex, arr.get(index)); | |
arr.set(index, temp); | |
heapDown(largerValueIndex); | |
} | |
} | |
public int size() { | |
return arr.size(); | |
} | |
public void insert(int... values) { | |
for (int v : values) { | |
arr.add(v); | |
heapUp(arr.size() - 1); | |
} | |
} | |
public int delete() { | |
if (arr.size() == 0) throw new ArrayIndexOutOfBoundsException(); | |
int removed = arr.remove(0); | |
if (arr.size() != 0) | |
arr.add(0, arr.remove(arr.size() - 1)); | |
heapDown(0); | |
return removed; | |
} | |
public void printArray() { | |
arr.forEach(System.out::println); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment