Add a min-max heap implementation that can be used to back a priority queue (#61)

* Add PriorityQueue implementation built on top of a MinMaxHeap

* Merge MinMaxHeap into PriorityQueue

* Add `unordered` read-only view into underlying heap

* Start filling in PriorityQueue benchmarks

* Implement our own swapAt()

storage.swapAt exhibits excessive allocations

* Rename _delete(at:) to _remove(at:)

* Rename removeMin/removeMax -> popMin/popMax

* Use magic values 1, 2 to refer to the items in the first max level

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>

* Specify logarithmic complexities as "O(log `count`) / 2" instead of "O(log n)"

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>

* Clarify logic in popMax

* Simplify logic in _remove(at:)

* Move the bounds checking into the various index computation methods

They will all now return `nil` for invalid indices.

* Floyd's heap construction algorithm should start from count/2 - 1

* Add ObjC wrapper around CFBinaryHeap to benchmarks

* Fix benchmarks that broke because of renames

* Add removeMin/removeMax

* Make _minMaxHeapIsMinLevel an instance method

* Split _indexOfChildOrGrandchild(of:sortedUsing:) into two separate functions

There is a large performance cost with passing a predicate function.

* Defer comparing children when determining largest/smallest descendant

If the given index has 4 grandchildren, we can skip comparing the children.

* Added an iterator of the min and max views to the priority queue

* seperated iterator implementation into a new file

* Use renamed popMin/Max in Iterator instead of removeMin/Max

* Fix code formatting

Indentation of 2 spaces and 80 char column width

* Add sequence initializer

* Fix code formatting in benchmarks

* Fix benchmark names

* Remove init from Collection

This should already be handled by the init from Sequence

* Add conformance to ExpressibleByArrayLiteral

* Move ExpressibleByArrayLiteral conformance to separate file

* Update PriorityQueue's CMakeLists.txt

* Make ascending and descending iterators public

* Inline ALL THE THINGS!

* Iterative instead of recursive implementation, @inline(__always) a couple more critical functions.

* Address PR feedback, thanks!

* Check invariants on insertion and deletion

* Minor code formatting cleanup

* Add copyright header to test file

* Fix missing empty line

* Add naïve implementation of insert(contentsOf:)

* Add documentation on complexity of init<S:Sequence>(_:)

* Cite source paper in documentation

* Rename PriorityQueue -> MinMaxHeap

We'll be reintroducing the PriorityQueue type as a wrapper.

* Mark insert(contentsOf:) as inlinable

This results in ~10x speedup in my initial tests.

* Rename argument label "startingAt" -> "elementAt"

These functions used to be recursive, so "startingAt" made sense.
Now that they're iterative, we should fix the label.

* Remove coefficients from complexity docs

* Make `_minMaxHeapIsMinLevel` take an index instead of a count

* Rename MinMaxHeap -> Heap

* Add documentation for Heap

* Make Heap.Iterator init and direction internal

* Fix reference to queue in documentation

Co-authored-by: Dante Broggi <34220985+Dante-Broggi@users.noreply.github.com>

* Don't wrap integers in CFBinaryHeap benchmark in NSNumber

* Avoid heap allocation altogether

* Add table with performance of operations

* Add heap performance graph

* Apply suggestions from code review

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

* Make _checkInvariants comments a doc comment

* Split Heap.Iterator into two separate views

Adapted from Daryle Walker's (github.com/CTMacUser) suggestions

* Prefix heap storage variable with an underscore

* Update benchmark image

* Fix Sources/PriorityQueueModule/CMakeLists.txt

Heap+Iterator.swift was renamed to Heap+OrderedViews.swift

Co-authored-by: Karoy Lorentey <klorentey@apple.com>

* CFBinaryHeap is only available on Darwin

* CFBinaryHeap is only available on Darwin

* CFBinaryHeap is only available on Darwin

Co-authored-by: Tim Vermeulen <tvermeulen@apple.com>
Co-authored-by: Amanuel Ephem <amanuelephrem776@gmail.com>
Co-authored-by: Joakim Hassila <joj@mac.com>
Co-authored-by: Dante Broggi <34220985+Dante-Broggi@users.noreply.github.com>
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
This commit is contained in:
authored and GitHub committed 2021-08-06 22:21:23 -07:00
1 parent 0959ba76a1
commit 940c963bc4
22 files changed
+1721 -3

No files matched your search

@@ -0,0 +1,19 @@
#[[
This source file is part of the Swift Collections Open Source Project
Copyright (c) 2021 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See https://swift.org/LICENSE.txt for license information
#]]
add_library(PriorityQueueModule
Heap.swift
Heap+ExpressibleByArrayLiteral.swift
Heap+Invariants.swift
Heap+OrderedViews.swift)
set_target_properties(PriorityQueueModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(PriorityQueueModule)
set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS PriorityQueueModule)
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Heap: ExpressibleByArrayLiteral {
/// Creates a new heap from the contents of an array literal.
///
/// **Do not call this initializer directly.** It is used by the compiler when
/// you use an array literal. Instead, create a new heap using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a heap is expected
/// by the type context.
///
/// - Parameter elements: A variadic list of elements of the new set.
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
@@ -0,0 +1,97 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Swift
import Foundation
extension Heap {
#if COLLECTIONS_INTERNAL_CHECKS
/// Iterates through all the levels in the heap, ensuring that items in min
/// levels are smaller than all their descendants and items in max levels
/// are larger than all their descendants.
///
/// The min-max heap indices are structured like this:
///
/// ```
/// min 0
/// max 1 2
/// min 3 4 5 6
/// max 7 8 9 10 11 12 13 14
/// min 15...
/// ...
/// ```
///
/// The iteration happens in depth-first order, so the descendants of the
/// element at index 0 are checked to ensure they are >= that element. This is
/// repeated for each child of the element at index 0 (inverting the
/// comparison at each level).
///
/// In the case of 7 elements total (spread across 3 levels), the checking
/// happens in the following order:
///
/// ```
/// compare >= 0: 1, 3, 4, 2, 5, 6
/// compare <= 1: 3, 4
/// compare >= 3: (no children)
/// compare >= 4: (no children)
/// compare <= 2: 5, 6
/// compare >= 5: (no children)
/// compare >= 6: (no children)
/// ```
@inlinable
@inline(never)
internal func _checkInvariants() {
guard count > 1 else { return }
var indicesToVisit: [Int] = [0]
while let elementIdx = indicesToVisit.popLast() {
let element = _storage[elementIdx]
let isMinLevel = _minMaxHeapIsMinLevel(elementIdx)
var descendantIndicesToVisit = [Int]()
// Add the children of this element to the outer loop (as we want to check
// that they are >= or <= their descendants as well)
if let rightIdx = _rightChildIndex(of: elementIdx) {
descendantIndicesToVisit.append(rightIdx)
indicesToVisit.append(rightIdx)
}
if let leftIdx = _leftChildIndex(of: elementIdx) {
descendantIndicesToVisit.append(leftIdx)
indicesToVisit.append(leftIdx)
}
// Compare the current element against its descendants
while let idx = descendantIndicesToVisit.popLast() {
if isMinLevel {
precondition(element <= _storage[idx],
"Element '\(_storage[idx])' at index \(idx) should be >= '\(element)'")
} else {
precondition(element >= _storage[idx],
"Element '\(_storage[idx])' at index \(idx) should be <= '\(element)'")
}
if let rightIdx = _rightChildIndex(of: idx) {
descendantIndicesToVisit.append(rightIdx)
}
if let leftIdx = _leftChildIndex(of: idx) {
descendantIndicesToVisit.append(leftIdx)
}
}
}
}
#else
@inlinable
@inline(__always)
public func _checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
}
@@ -0,0 +1,60 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Heap {
/// A view of a `Heap`'s elements, as a `Sequence` from the smallest to
/// largest element.
public struct AscendingView: Sequence, IteratorProtocol {
@usableFromInline
internal var _base: Heap
/// Creates an ascending-element view from the given heap.
@inlinable
init(_base: Heap) {
self._base = _base
}
@inlinable
public mutating func next() -> Element? {
return _base.popMin()
}
}
/// A view of a `Heap`'s elements, as a `Sequence` from the largest to
/// smallest element.
public struct DescendingView: Sequence, IteratorProtocol {
@usableFromInline
internal var _base: Heap
/// Creates a descending-element view from the given heap.
@inlinable
init(_base: Heap) {
self._base = _base
}
@inlinable
public mutating func next() -> Element? {
return _base.popMax()
}
}
/// Returns an iterator that orders elements from smallest to largest
@inlinable
public var ascending: AscendingView {
return AscendingView(_base: self)
}
/// Returns an iterator that orders elements from largest to smallest
@inlinable
public var descending: DescendingView {
return DescendingView(_base: self)
}
}
+533
View File
@@ -0,0 +1,533 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import Swift
/// A [Min-Max Heap](https://en.wikipedia.org/wiki/Min-max_heap) data structure.
///
/// In a min-max heap, each node at an even level in the tree is less than all
/// its descendants, while each node at an odd level in the tree is greater than
/// all of its descendants.
///
/// The implementation is based off [Atkinson et al. Min-Max Heaps and
/// Generalized Priority Queues (1986)](http://akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf).
///
/// M.D. Atkinson, J.-R. Sack, N. Santoro, T. Strothotte. October 1986.
/// Min-Max Heaps and Generalized Priority Queues. Communications of the ACM.
/// 29(10):996-1000.
public struct Heap<Element: Comparable> {
@usableFromInline
internal var _storage: [Element]
/// A Boolean value indicating whether or not the heap is empty.
///
/// - Complexity: O(1)
@inlinable
public var isEmpty: Bool {
_storage.isEmpty
}
/// The number of elements in the heap.
///
/// - Complexity: O(1)
@inlinable
public var count: Int {
_storage.count
}
/// A read-only view into the underlying array.
///
/// Note: The elements aren't _arbitrarily_ ordered (it is, after all, a
/// heap). However, no guarantees are given as to the ordering of the elements
/// or that this won't change in future versions of the library.
///
/// - Complexity: O(1)
@inlinable
public var unordered: [Element] {
_storage
}
/// Creates an empty heap.
@inlinable
public init() {
_storage = []
}
/// Inserts the given element into the heap.
///
/// - Complexity: O(log `count`)
@inlinable
public mutating func insert(_ element: Element) {
_storage.append(element)
_bubbleUp(elementAt: _storage.endIndex - 1)
_checkInvariants()
}
/// Returns the element with the lowest priority, if available.
///
/// - Complexity: O(1)
@inlinable
public func min() -> Element? {
_storage.first
}
/// Returns the element with the highest priority, if available.
///
/// - Complexity: O(1)
@inlinable
public func max() -> Element? {
switch _storage.count {
case 0, 1, 2:
// If count is 0, `last` will return `nil`
// If count is 1, the last (and only) item is the max
// If count is 2, the last item is the max (as it's the only item in the
// first max level)
return _storage.last
default:
// We have at least 3 items -- return the larger of the two in the first
// max level
return Swift.max(_storage[1], _storage[2])
}
}
/// Removes and returns the element with the lowest priority, if available.
///
/// - Complexity: O(log `count`)
@inlinable
public mutating func popMin() -> Element? {
defer { _checkInvariants() }
return _remove(at: 0)
}
/// Removes and returns the element with the highest priority, if available.
///
/// - Complexity: O(log `count`)
@inlinable
public mutating func popMax() -> Element? {
defer { _checkInvariants() }
switch _storage.count {
case 0, 1, 2:
// If count is 0, `popLast` will return `nil`
// If count is 1, the last (and only) item is the max
// If count is 2, the last item is the max (as it's the only item in the
// first max level)
return _storage.popLast()
default:
// The max item is the larger of the two items in the first max level
let maxIdx = _storage[2] > _storage[1] ? 2 : 1
return _remove(at: maxIdx)
}
}
/// Removes and returns the element with the lowest priority.
///
/// The heap *must not* be empty.
///
/// - Complexity: O(log `count`)
@inlinable
public mutating func removeMin() -> Element {
return popMin()!
}
/// Removes and returns the element with the highest priority.
///
/// The heap *must not* be empty.
///
/// - Complexity: O(log `count`)
@inlinable
public mutating func removeMax() -> Element {
return popMax()!
}
// MARK: -
@inline(__always)
@inlinable
internal mutating func _bubbleUp(elementAt index: Int) {
guard let parentIdx = _parentIndex(of: index) else {
// We're already at the root -- can't go any further
return
}
// Figure out if `index` is on an even or odd level
let levelIsMin = _minMaxHeapIsMinLevel(index)
if levelIsMin {
if _storage[index] > _storage[parentIdx] {
_swapAt(index, parentIdx)
_bubbleUpMax(elementAt: parentIdx)
} else {
_bubbleUpMin(elementAt: index)
}
} else {
if _storage[index] < _storage[parentIdx] {
_swapAt(index, parentIdx)
_bubbleUpMin(elementAt: parentIdx)
} else {
_bubbleUpMax(elementAt: index)
}
}
}
@inline(__always)
@inlinable
internal mutating func _bubbleUpMin(elementAt index: Int) {
var index = index
while let grandparentIdx = _grandparentIndex(of: index),
_storage[index] < _storage[grandparentIdx] {
_swapAt(index, grandparentIdx)
index = grandparentIdx
}
}
@inline(__always)
@inlinable
internal mutating func _bubbleUpMax(elementAt index: Int) {
var index = index
while let grandparentIdx = _grandparentIndex(of: index),
_storage[index] > _storage[grandparentIdx] {
_swapAt(index, grandparentIdx)
index = grandparentIdx
}
}
// MARK: -
@discardableResult
@inlinable
internal mutating func _remove(at index: Int) -> Element? {
guard _storage.count > index else {
return nil
}
var removed = _storage.removeLast()
if index < _storage.count {
swap(&removed, &_storage[index])
_trickleDown(elementAt: index)
}
return removed
}
// MARK: -
@inline(__always)
@inlinable
internal mutating func _trickleDown(elementAt index: Int) {
// Figure out if `index` is on an even or odd level
let levelIsMin = _minMaxHeapIsMinLevel(index)
if levelIsMin {
_trickleDownMin(elementAt: index)
} else {
_trickleDownMax(elementAt: index)
}
}
@inline(__always)
@inlinable
internal mutating func _trickleDownMin(elementAt index: Int) {
var index = index
while let (smallestDescendantIdx, isChild) =
_indexOfLowestPriorityChildOrGrandchild(of: index) {
if _storage[smallestDescendantIdx] < _storage[index] {
_swapAt(smallestDescendantIdx, index)
if isChild {
return
}
// Smallest is a grandchild
let parentIdx = _parentIndex(of: smallestDescendantIdx)!
if _storage[smallestDescendantIdx] > _storage[parentIdx] {
_swapAt(smallestDescendantIdx, parentIdx)
}
index = smallestDescendantIdx
} else {
return
}
}
}
@inline(__always)
@inlinable
internal mutating func _trickleDownMax(elementAt index: Int) {
var index = index
while let (largestDescendantIdx, isChild) =
_indexOfHighestPriorityChildOrGrandchild(of: index) {
if _storage[largestDescendantIdx] > _storage[index] {
_swapAt(largestDescendantIdx, index)
if isChild {
return
}
// Largest is a grandchild
let parentIdx = _parentIndex(of: largestDescendantIdx)!
if _storage[largestDescendantIdx] < _storage[parentIdx] {
_swapAt(largestDescendantIdx, parentIdx)
}
index = largestDescendantIdx
} else {
return
}
}
}
/// Returns the lowest priority child or grandchild of the element at the
/// given index.
///
/// Returns `nil` if the element has no descendants.
///
/// - parameter index: The index of the element whose descendants should be
/// compared.
@inline(__always)
@inlinable
internal func _indexOfLowestPriorityChildOrGrandchild(
of index: Int
) -> (index: Int, isChild: Bool)? {
guard let leftChildIdx = _leftChildIndex(of: index) else {
return nil
}
var result: (index: Int, isChild: Bool) = (leftChildIdx, true)
guard let rightChildIdx = _rightChildIndex(of: index) else {
return result
}
guard let firstGrandchildIdx = _firstGrandchildIndex(of: index),
let lastGrandchildIdx = _lastGrandchildIndex(of: index)
else {
// We have no grandchildren -- compare the two children instead
if _storage[rightChildIdx] < _storage[leftChildIdx] {
result.index = rightChildIdx
}
return result
}
// If we have 4 grandchildren, we can skip comparing the children as the
// heap invariants will ensure that the grandchildren will be smaller.
// Otherwise, we need to do the comparison.
if lastGrandchildIdx != firstGrandchildIdx + 3 {
// Compare the two children
if _storage[rightChildIdx] < _storage[leftChildIdx] {
result.index = rightChildIdx
}
}
// Iterate through the grandchildren
for i in firstGrandchildIdx...lastGrandchildIdx {
if _storage[i] < _storage[result.index] {
result.index = i
result.isChild = false
}
}
return result
}
/// Returns the highest priority child or grandchild of the element at the
/// given index.
///
/// Returns `nil` if the element has no descendants.
///
/// - parameter index: The index of the item whose descendants should be
/// compared.
@inline(__always)
@inlinable
internal func _indexOfHighestPriorityChildOrGrandchild(
of index: Int
) -> (index: Int, isChild: Bool)? {
guard let leftChildIdx = _leftChildIndex(of: index) else {
return nil
}
var result: (index: Int, isChild: Bool) = (leftChildIdx, true)
guard let rightChildIdx = _rightChildIndex(of: index) else {
return result
}
guard let firstGrandchildIdx = _firstGrandchildIndex(of: index),
let lastGrandchildIdx = _lastGrandchildIndex(of: index)
else {
// We have no grandchildren -- compare the two children instead
if _storage[rightChildIdx] > _storage[leftChildIdx] {
result.index = rightChildIdx
}
return result
}
// If we have 4 grandchildren, we can skip comparing the children as the
// heap invariants will ensure that the grandchildren will be larger.
// Otherwise, we need to do the comparison.
if lastGrandchildIdx != firstGrandchildIdx + 3 {
// Compare the two children
if _storage[rightChildIdx] > _storage[leftChildIdx] {
result.index = rightChildIdx
}
}
// Iterate through the grandchildren
for i in firstGrandchildIdx...lastGrandchildIdx {
if _storage[i] > _storage[result.index] {
result.index = i
result.isChild = false
}
}
return result
}
// MARK: - Helpers
/// Returns `true` if `index` falls on a min level in a min-max heap.
///
/// - Precondition: `index` must be non-negative.
@inline(__always)
@inlinable
internal func _minMaxHeapIsMinLevel(_ index: Int) -> Bool {
precondition(index >= 0)
return (index + 1)._binaryLogarithm() & 0b1 == 0
}
/// Swaps the elements in the heap at the given indices.
@inline(__always)
@inlinable
internal mutating func _swapAt(_ i: Int, _ j: Int) {
let tmp = _storage[i]
_storage[i] = _storage[j]
_storage[j] = tmp
}
/// Returns the parent index of the given `index`
/// or `nil` if the index has no parent (i.e. `index == 0`).
@inline(__always)
@inlinable
internal func _parentIndex(of index: Int) -> Int? {
guard index > 0 else {
return nil
}
return (index - 1) / 2
}
/// Returns the grandparent index of the given `index`
/// or `nil` if the index has no grandparent.
@inline(__always)
@inlinable
internal func _grandparentIndex(of index: Int) -> Int? {
guard index > 2 else {
return nil
}
return (index - 3) / 4
}
/// Returns the first child index of the given `index`
/// or `nil` if the index has no children.
@inline(__always)
@inlinable
internal func _leftChildIndex(of index: Int) -> Int? {
let childIdx = index * 2 + 1
guard childIdx < _storage.count else {
return nil
}
return childIdx
}
/// Returns the right child index of the given `index`
/// or `nil` if the index has no right child.
@inline(__always)
@inlinable
internal func _rightChildIndex(of index: Int) -> Int? {
let childIdx = index * 2 + 2
guard childIdx < _storage.count else {
return nil
}
return childIdx
}
/// Returns the first grandchild index of the given `index`
/// or `nil` if the index has no grandchildren.
@inline(__always)
@inlinable
internal func _firstGrandchildIndex(of index: Int) -> Int? {
let grandchildIdx = index * 4 + 3
guard grandchildIdx < _storage.count else {
return nil
}
return grandchildIdx
}
/// Returns the last valid grandchild index of the given `index`
/// or `nil` if the index has no grandchildren.
///
/// In cases where the given index only has one grandchild, the index
/// returned by this function is the same as that returned by
/// `_firstGrandchildIndex`.
@inline(__always)
@inlinable
internal func _lastGrandchildIndex(of index: Int) -> Int? {
guard _firstGrandchildIndex(of: index) != nil else {
// There are no grandchildren of the node at `index`
return nil
}
return Swift.min(index * 4 + 6, _storage.count - 1)
}
}
// MARK: -
extension Heap {
/// Initializes a heap from a sequence.
///
/// Utilizes [Floyd's linear-time heap construction algorithm](https://en.wikipedia.org/wiki/Heapsort#Floyd's_heap_construction).
///
/// - Complexity: O(n), where `n` is the length of `elements`.
@inlinable
public init<S: Sequence>(_ elements: S) where S.Element == Element {
_storage = Array(elements)
for idx in (0 ..< (_storage.count / 2)).reversed() {
_trickleDown(elementAt: idx)
}
_checkInvariants()
}
/// Inserts the elements in the given sequence into the heap.
///
/// - Parameter newElements: The new elements to insert into the heap.
///
/// - Complexity: O(n * log `count`), where `n` is the length of `newElements`.
@inlinable
public mutating func insert<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
for element in newElements {
insert(element)
}
}
}