Heap

public struct Heap<T>
  • Creates an empty heap. The sort function determines whether this is a min-heap or max-heap. For comparable data types, > makes a max-heap, < makes a min-heap.

    Declaration

    Swift

    public init(sort: @escaping (T, T) -> Bool)
  • Creates a heap from an array. The order of the array does not matter; the elements are inserted into the heap in the order determined by the sort function. For comparable data types, ‘>’ makes a max-heap, ‘<’ makes a min-heap.

    Declaration

    Swift

    public init(array: [T], sort: @escaping (T, T) -> Bool)
  • Declaration

    Swift

    public var isEmpty: Bool { get }
  • Declaration

    Swift

    public var count: Int { get }
  • Returns the maximum value in the heap (for a max-heap) or the minimum value (for a min-heap).

    Declaration

    Swift

    public func peek() -> T?
  • Adds a new value to the heap. This reorders the heap so that the max-heap or min-heap property still holds. Performance: O(log n).

    Declaration

    Swift

    public mutating func insert(_ value: T)
  • Adds a sequence of values to the heap. This reorders the heap so that the max-heap or min-heap property still holds. Performance: O(log n).

    Declaration

    Swift

    public mutating func insert<S>(_ sequence: S) where T == S.Element, S : Sequence
  • Allows you to change an element. This reorders the heap so that the max-heap or min-heap property still holds.

    Declaration

    Swift

    public mutating func replace(index i: Int, value: T)
  • Removes the root node from the heap. For a max-heap, this is the maximum value; for a min-heap it is the minimum value. Performance: O(log n).

    Declaration

    Swift

    @discardableResult
    public mutating func remove() -> T?
  • Removes an arbitrary node from the heap. Performance: O(log n). Note that you need to know the node’s index.

    Declaration

    Swift

    @discardableResult
    public mutating func remove(at index: Int) -> T?