Min Heap in Java: Complete Implementation
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Java's strong typing and generics make Min Heap robust and reusable.
- ✓The implementation achieves O(log n) average time complexity.
- ✓Java Collections Framework complements custom Min Heap implementations.
- ✓JUnit tests ensure correctness across edge cases.
- ✓push and pop are O(log n) and peek is O(1)
- ✓Priority queues in Dijkstra, Prim and A* search
Min Heap in Java: Overview
Java Implementation
// Min-heap in Java: array-backed binary heap
import java.util.ArrayList;
import java.util.List;
public class MinHeap {
private final List<Integer> data = new ArrayList<>();
void push(int value) {
data.add(value);
int i = data.size() - 1;
while (i > 0) {
int parent = (i - 1) / 2;
if (data.get(parent) <= data.get(i)) break;
swap(parent, i);
i = parent;
}
}
int pop() {
int top = data.get(0);
int last = data.remove(data.size() - 1);
if (!data.isEmpty()) {
data.set(0, last);
int i = 0, n = data.size();
while (true) {
int left = 2 * i + 1, right = 2 * i + 2, smallest = i;
if (left < n && data.get(left) < data.get(smallest)) smallest = left;
if (right < n && data.get(right) < data.get(smallest)) smallest = right;
if (smallest == i) break;
swap(i, smallest);
i = smallest;
}
}
return top;
}
private void swap(int a, int b) {
int tmp = data.get(a);
data.set(a, data.get(b));
data.set(b, tmp);
}
public static void main(String[] args) {
MinHeap heap = new MinHeap();
for (int v : new int[]{5, 3, 8, 1, 9, 2}) heap.push(v);
StringBuilder out = new StringBuilder();
for (int i = 0; i < 6; i++) out.append(heap.pop()).append(i < 5 ? " " : "");
System.out.println(out);
}
}Algorithm Steps in Java
Did You Get the Big O Right? NexusBro Will Tell You in Seconds.
Paste your algorithm. Get complexity analysis, edge cases, and optimizations.
Test My AlgorithmComplexity Analysis
Java Best Practices
JUnit Testing
When to Reach for Min Heap on the JVM
Min Heap in Production Java Systems
Frequently Asked Questions
How does Java's Arrays.sort compare to Min Heap?
Java's Arrays.sort uses dual-pivot Quicksort for primitives and TimSort for objects. Both achieve O(n log n) average case. Custom implementations of Min Heap are valuable for learning and for specialized requirements that the standard library does not address.
Should I use generics for Min Heap in Java?
Yes, generics make your Min Heap implementation reusable and type-safe. Use bounded type parameters like <T extends Comparable<? super T>> to ensure elements can be compared while maintaining flexibility for different types.
Is Java good for algorithm interviews?
Java is excellent for interviews. Its verbosity makes logic explicit, generics demonstrate type system knowledge, and the Collections Framework is well-known to interviewers. Most major companies accept Java for coding interviews.
How do I optimize Min Heap in Java?
Use primitive arrays to avoid autoboxing, minimize object allocation in loops, leverage System.arraycopy for bulk operations, and ensure your code is JIT-friendly by avoiding polymorphic call sites in hot paths. Profile with JMH for accurate benchmarks.
Can I use Min Heap Java code in Android?
Yes, Java algorithm implementations work in Android. Be mindful of memory constraints on mobile devices and consider the algorithm's space complexity. Android uses ART runtime, which handles generics and arrays similarly to standard JVM.
Why is building a heap O(n) and not O(n log n)?
Bottom-up heapify sifts down from the last parent to the root. Half the nodes are leaves and move zero levels, a quarter move at most one, and so on. That sum converges to a constant times n.
How do I get a max-heap from a min-heap?
Flip the comparison, or store negated keys. In Python's heapq, pushing -x and negating on pop is the usual trick.
Is a heap the same as a sorted array?
No. A heap only promises that each parent is no larger than its children. The second smallest element is one of the root's children, but the rest of the array is not in sorted order.
When should I use a heap instead of sorting?
When items arrive over time or you only need the smallest few. Sorting costs O(n log n) once; a heap gives you the current minimum after every insertion for O(log n) each.
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Replit offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.