Heap data structure (Min Heap implementation) A heap is a specialized tree-based data structure that satisfies the heap property: In a min heap, for any given node I, the value of I is less than or equal to the values of its children.

Note: This class shares similar implementation with PriorityQueue. The separation is intentional to provide distinct abstractions - Heap focuses on the data structure itself, while PriorityQueue provides a queue-like interface.

Example

const heap = new Heap();
heap.insert(5);
heap.insert(3);
heap.insert(7);
heap.peek(); // 3
heap.extract(); // 3
heap.peek(); // 5

Type Parameters

  • T

Hierarchy

  • Heap

Constructors

  • Type Parameters

    • T

    Parameters

    • comparator: ((a, b) => number) = Heap.defaultComparator
        • (a, b): number
        • Parameters

          • a: T
          • b: T

          Returns number

    Returns Heap<T>

Properties

comparator: ((a, b) => number)

Type declaration

    • (a, b): number
    • Parameters

      • a: T
      • b: T

      Returns number

data: T[]

Methods

  • Moves an element down the heap to maintain heap property

    Parameters

    • index: number

    Returns void

  • Moves an element up the heap to maintain heap property

    Parameters

    • index: number

    Returns void

  • Inserts a new element into the heap

    Parameters

    • value: T

    Returns void

  • Swaps two elements in the heap

    Parameters

    • i: number
    • j: number

    Returns void

  • Default comparator for min heap (smaller values have higher priority)

    Parameters

    • a: any
    • b: any

    Returns number

Generated using TypeDoc