08-heaps
Top-K with a Heap
Keep only the largest k values by maintaining a small min-heap.
Algorithm
Steps
- Store the heap in an array.
- Compare parent and child indexes instead of building explicit tree nodes.
- Swap only when the heap order is violated.
- Print the deterministic final heap state for replay comparison.
Complexity
- Time: O(n log k)
- Space: O(k)
bounded heap
For top-k largest values, a min-heap of size k keeps the current cutoff at the root.
Kotlin DSA Implementation
basic.kt
fun listString(values: List<Int>) = values.joinToString(", ", "[", "]")
fun heapInsert(heap: MutableList<Int>, value: Int) {
heap.add(value)
var child = heap.lastIndex
while (child > 0) {
val parent = (child - 1) / 2
if (heap[parent] <= heap[child]) break
val tmp = heap[parent]; heap[parent] = heap[child]; heap[child] = tmp
child = parent
}
}
fun heapPop(heap: MutableList<Int>): Int {
val smallest = heap[0]
heap[0] = heap.removeAt(heap.lastIndex)
var parent = 0
while (true) {
val left = parent * 2 + 1
val right = left + 1
if (left >= heap.size) break
var child = left
if (right < heap.size && heap[right] < heap[left]) child = right
if (heap[parent] <= heap[child]) break
val tmp = heap[parent]; heap[parent] = heap[child]; heap[child] = tmp
parent = child
}
return smallest
}
fun main() { val heap = mutableListOf<Int>(); for (value in listOf(5, 1, 9, 3, 7, 2)) { heapInsert(heap, value); if (heap.size > 3) heapPop(heap) }; val top = heap.sortedDescending(); println(listString(top)) }
Output
[9, 7, 5]
Implementation notes
- Kotlin keeps the working heap in
val heap = mutableListOf<Int>(), aMutableList<Int>whose binding is stable while helper calls mutate its contents. - The input stream is
listOf(5, 1, 9, 3, 7, 2). Each loop value is inserted withheapInsert(heap, value). heapInsertappends withheap.add(value), then sifts up usingheap.lastIndex, parent index(child - 1) / 2, min-heap comparisonheap[parent] <= heap[child], and explicit temp-variable swaps.- Size is bounded by
if (heap.size > 3) heapPop(heap), so values are inserted first and then the current minimum is evicted when the heap grows pastk. heapPopremoves the cutoff value by copyingheap[0], replacing the root withheap.removeAt(heap.lastIndex), and sifting down with child indexesparent * 2 + 1andleft + 1.- Evicted values are not collected; the retained heap holds the top three values as a min-heap.
- The trace shows heap states
[5],[1, 5],[1, 5, 9],[3, 5, 9],[5, 7, 9], and[5, 7, 9]after considering2. val top = heap.sortedDescending()creates the output list in high-to-low order, andprintln(listString(top))prints[9, 7, 5].