Keep only the largest k values by maintaining a small min-heap.

Algorithm

Steps

  1. Store the heap in an array.
  2. Compare parent and child indexes instead of building explicit tree nodes.
  3. Swap only when the heap order is violated.
  4. 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.

C# DSA Implementation

basic.cs
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
    static string ListString(IEnumerable<int> values) => "[" + string.Join(", ", values) + "]";
    static void HeapInsert(List<int> heap, int value) {
        heap.Add(value);
        int child = heap.Count - 1;
        while (child > 0) {
            int parent = (child - 1) / 2;
            if (heap[parent] <= heap[child]) break;
            (heap[parent], heap[child]) = (heap[child], heap[parent]);
            child = parent;
        }
    }
    static int HeapPop(List<int> heap) {
        int smallest = heap[0];
        heap[0] = heap[^1];
        heap.RemoveAt(heap.Count - 1);
        int parent = 0;
        while (true) {
            int left = parent * 2 + 1, right = left + 1;
            if (left >= heap.Count) break;
            int child = left;
            if (right < heap.Count && heap[right] < heap[left]) child = right;
            if (heap[parent] <= heap[child]) break;
            (heap[parent], heap[child]) = (heap[child], heap[parent]);
            parent = child;
        }
        return smallest;
    }
    static void Main() { var heap = new List<int>(); foreach (var value in new[] {5, 1, 9, 3, 7, 2}) { HeapInsert(heap, value); if (heap.Count > 3) HeapPop(heap); } heap.Sort((a, b) => b.CompareTo(a)); Console.WriteLine(ListString(heap)); }
}

Output

[9, 7, 5]

Implementation notes

  • This version uses a custom min-heap over List<int>, not PriorityQueue<TElement,TPriority>. heap.Add(value) appends into the managed backing array, and any resized storage is handled by the CLR and GC.
  • The helpers keep int values in place with index arithmetic and tuple swaps: inserts sift up with (child - 1) / 2, and overflow past k calls HeapPop to move heap[^1] to the root, RemoveAt the last slot, and sift down by comparing left = parent * 2 + 1 with right = left + 1.
  • The replay shows the bounded heap after each input value. The final heap.Sort((a, b) => b.CompareTo(a)) changes only the printed order from the retained min-heap [5, 7, 9] to [9, 7, 5].