diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme
new file mode 100644
index 00000000..b34d2227
--- /dev/null
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/PriorityQueueModule.xcscheme
@@ -0,0 +1,77 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
index efc01154..bf3d7efa 100644
--- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
+++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
@@ -132,6 +132,20 @@
ReferencedContainer = "container:">
+
+
+
+
+
+
+
+
+
+
+
+
init from range",
+ "Heap insert",
+ "Heap insert(contentsOf:)",
+ "Heap popMax",
+ "Heap popMin"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "initializers",
+ "tasks": [
+ "Heap init from range"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "insert",
+ "tasks": [
+ "Heap insert",
+ "Heap insert(contentsOf:)"
+ ]
+ },
+ {
+ "kind": "chart",
+ "title": "remove",
+ "tasks": [
+ "Heap popMax",
+ "Heap popMin"
+ ]
+ }
+ ]
+ },
{
"kind": "group",
"title": "Against other Swift collections",
diff --git a/Benchmarks/Benchmarks/PriorityQueueBenchmarks.swift b/Benchmarks/Benchmarks/PriorityQueueBenchmarks.swift
new file mode 100644
index 00000000..750f7173
--- /dev/null
+++ b/Benchmarks/Benchmarks/PriorityQueueBenchmarks.swift
@@ -0,0 +1,122 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 CollectionsBenchmark
+import PriorityQueueModule
+import CppBenchmarks
+
+extension Benchmark {
+ public mutating func addHeapBenchmarks() {
+ self.addSimple(
+ title: "Heap init from range",
+ input: Int.self
+ ) { size in
+ blackHole(Heap(0.. insert",
+ input: [Int].self
+ ) { input in
+ var queue = Heap()
+ for i in input {
+ queue.insert(i)
+ }
+ precondition(queue.count == input.count)
+ blackHole(queue)
+ }
+
+ self.add(
+ title: "Heap insert(contentsOf:)",
+ input: ([Int], [Int]).self
+ ) { (existing, new) in
+ return { timer in
+ var queue = Heap(existing)
+ queue.insert(contentsOf: new)
+ precondition(queue.count == existing.count + new.count)
+ blackHole(queue)
+ }
+ }
+
+ self.add(
+ title: "Heap popMax",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ var queue = Heap(input)
+ timer.measure {
+ while let max = queue.popMax() {
+ blackHole(max)
+ }
+ }
+ precondition(queue.isEmpty)
+ blackHole(queue)
+ }
+ }
+
+ self.add(
+ title: "Heap popMin",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ var queue = Heap(input)
+ timer.measure {
+ while let min = queue.popMin() {
+ blackHole(min)
+ }
+ }
+ precondition(queue.isEmpty)
+ blackHole(queue)
+ }
+ }
+ }
+}
+
+// MARK: -
+
+extension Benchmark {
+ public mutating func addCFBinaryHeapBenchmarks() {
+ #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
+ self.addSimple(
+ title: "CFBinaryHeap insert",
+ input: [Int].self
+ ) { input in
+ let heap = BinaryHeap()
+ for i in input {
+ heap.insert(i)
+ }
+ precondition(heap.count == input.count)
+ blackHole(heap)
+ }
+
+ self.add(
+ title: "CFBinaryHeap removeMinimumValue",
+ input: [Int].self
+ ) { input in
+ return { timer in
+ let heap = BinaryHeap()
+ for i in input {
+ heap.insert(i)
+ }
+
+ timer.measure {
+ while heap.count > 0 {
+ let min = heap.popMinimum()
+ blackHole(min)
+ }
+ }
+ precondition(heap.count == 0)
+ blackHole(heap)
+ }
+ }
+ #endif
+ }
+}
diff --git a/Benchmarks/CppBenchmarks/include/BinaryHeap.h b/Benchmarks/CppBenchmarks/include/BinaryHeap.h
new file mode 100644
index 00000000..cb586abf
--- /dev/null
+++ b/Benchmarks/CppBenchmarks/include/BinaryHeap.h
@@ -0,0 +1,29 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef BinaryHeap_h
+#define BinaryHeap_h
+
+#if __APPLE__ // CFBinaryHeap only exists on Apple platforms
+
+@import Foundation;
+
+@interface BinaryHeap: NSObject
+
+@property (nonatomic, readonly) NSUInteger count;
+
+- (void)insert:(NSInteger)value;
+- (NSInteger)popMinimum;
+
+@end
+
+#endif // __APPLE__
+#endif /* BinaryHeap_h */
diff --git a/Benchmarks/CppBenchmarks/include/module.modulemap b/Benchmarks/CppBenchmarks/include/module.modulemap
index 13fe2d39..7f45ce88 100644
--- a/Benchmarks/CppBenchmarks/include/module.modulemap
+++ b/Benchmarks/CppBenchmarks/include/module.modulemap
@@ -4,6 +4,6 @@ module CppBenchmarks {
header "DequeBenchmarks.h"
header "UnorderedSetBenchmarks.h"
header "UnorderedMapBenchmarks.h"
+ header "BinaryHeap.h"
export *
}
-
diff --git a/Benchmarks/CppBenchmarks/src/BinaryHeap.m b/Benchmarks/CppBenchmarks/src/BinaryHeap.m
new file mode 100644
index 00000000..e27cf84c
--- /dev/null
+++ b/Benchmarks/CppBenchmarks/src/BinaryHeap.m
@@ -0,0 +1,76 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#if __APPLE__ // CFBinaryHeap only exists on Apple platforms
+
+#import
+
+#import "BinaryHeap.h"
+
+@implementation BinaryHeap
+{
+ CFBinaryHeapRef _storage;
+}
+
+static CFComparisonResult HeapCompare(const void *lhs, const void *rhs, void *context)
+{
+ if ((NSInteger)lhs == (NSInteger)rhs) {
+ return kCFCompareEqualTo;
+ } else if ((NSInteger)lhs < (NSInteger)rhs) {
+ return kCFCompareLessThan;
+ } else {
+ return kCFCompareGreaterThan;
+ }
+}
+
+- (instancetype)init
+{
+ if ((self = [super init]))
+ {
+ CFBinaryHeapCallBacks callbacks = (CFBinaryHeapCallBacks){
+ .version = 0,
+ .retain = NULL,
+ .release = NULL,
+ .copyDescription = &CFCopyDescription,
+ .compare = &HeapCompare
+ };
+ _storage = CFBinaryHeapCreate(kCFAllocatorDefault, 0, &callbacks, NULL);
+ }
+
+ return self;
+}
+
+- (void)dealloc
+{
+ CFRelease(_storage);
+}
+
+- (NSUInteger)count
+{
+ return CFBinaryHeapGetCount(_storage);
+}
+
+- (void)insert:(NSInteger)value
+{
+ CFBinaryHeapAddValue(_storage, (const void *)value);
+}
+
+- (NSInteger)popMinimum
+{
+ const NSInteger val = (NSInteger)CFBinaryHeapGetMinimum(_storage);
+ CFBinaryHeapRemoveMinimumValue(_storage);
+
+ return val;
+}
+
+@end
+
+#endif // __APPLE__
diff --git a/Benchmarks/swift-collections-benchmark/main.swift b/Benchmarks/swift-collections-benchmark/main.swift
index ddfed857..0227f77d 100644
--- a/Benchmarks/swift-collections-benchmark/main.swift
+++ b/Benchmarks/swift-collections-benchmark/main.swift
@@ -19,6 +19,8 @@ benchmark.addDictionaryBenchmarks()
benchmark.addDequeBenchmarks()
benchmark.addOrderedSetBenchmarks()
benchmark.addOrderedDictionaryBenchmarks()
+benchmark.addHeapBenchmarks()
+benchmark.addCFBinaryHeapBenchmarks()
benchmark.addCppBenchmarks()
benchmark.chartLibrary = try benchmark.loadReferenceLibrary()
diff --git a/Documentation/Heap.md b/Documentation/Heap.md
new file mode 100644
index 00000000..8a37ec52
--- /dev/null
+++ b/Documentation/Heap.md
@@ -0,0 +1,162 @@
+# Heap
+
+A partially-ordered tree of elements with performant insertion and removal operations.
+
+## Declaration
+
+```swift
+public struct Heap
+```
+
+## Overview
+
+Array-backed [binary heaps](https://en.wikipedia.org/wiki/Heap_(data_structure)) provide performant lookups (`O(1)`) of the smallest or largest element (depending on whether it's a min-heap or a max-heap, respectively) as well as insertion and removal (`O(log n)`). Heaps are commonly used as the backing storage for a priority queue.
+
+A variant on this, the [min-max heap](https://en.wikipedia.org/wiki/Min-max_heap), allows for performant lookups and removal of both the smallest **and** largest elements by interleaving min and max levels in the backing array. `Heap` is an implementation of a min-max heap.
+
+### Initialization
+
+There are a couple of options for initializing a `Heap`. To create an empty `Heap`, call `init()`:
+
+```swift
+var heap = Heap()
+```
+
+You can also create a `Heap` from an existing sequence in linear time:
+
+```swift
+var heap = Heap((1...).prefix(20))
+```
+
+Finally, a `Heap` can be created from an array literal:
+
+```swift
+var heap: Heap = [0.1, 0.6, 1.0, 0.15, 0.42]
+```
+
+### Insertion
+
+#### Of a single element
+
+To insert an element into a `Heap`, call `insert(_:)`:
+
+```swift
+var heap = Heap()
+heap.insert(6)
+heap.insert(2)
+```
+
+This works by adding the new element into the end of the backing array and then bubbling it up to where it belongs in the heap.
+
+#### Of a sequence of elements
+
+You can also insert a sequence of elements into a `Heap`:
+
+```swift
+var heap = Heap((0..<10))
+heap.insert(contentsOf: (20...100).shuffled())
+heap.insert(contentsOf: [-5, -6, -8, -12, -3])
+```
+
+### Lookup
+
+As mentioned earlier, the smallest and largest elements can be queried in constant time:
+
+```swift
+var heap = Heap((1...20))
+let min = heap.min() // min = 1
+let max = heap.max() // max = 20
+```
+
+In a min-max heap, the smallest element is stored at index 0 in the backing array; the largest element is stored at either index 1 or index 2, the first max level in the heap (so to look up the largest, we compare the two and return the larger one).
+
+We also expose a read-only view into the backing array, should somebody need that.
+
+```swift
+let heap = Heap((1...100).shuffled())
+for val in heap.unordered {
+ ...
+}
+```
+
+> 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.
+
+### Removal
+
+Removal has logarithmic complexity, and removing both the smallest and largest elements is supported:
+
+```swift
+var heap = Heap((1...20).shuffled())
+var heap2 = heap
+
+while let min = heap.popMin() {
+ print("Next smallest element:", min)
+}
+
+while let max = heap2.popMax() {
+ print("Next largest element:", max)
+}
+```
+
+To remove the smallest element, we remove and return the element at index 0. The element at the end of the backing array is put in its place at index 0, and then we trickle it down to where it belongs in the heap. To remove the largest element, we do the same except the index is whatever the index of the largest element is (see above) instead of 0.
+
+We also have non-optional flavors that assume the heap isn't empty, `removeMin()` and `removeMax()`.
+
+### Iteration
+
+`Heap` itself doesn't conform to `Sequence` because of the potential confusion around which direction it should iterate (largest-to-smallest? smallest-to-largest?). Instead, we expose two iterators that conform to `Sequence`:
+
+```swift
+for val in heap.ascending {
+ ...
+}
+
+for val in heap.descending {
+ ...
+}
+```
+
+### Performance
+
+| Operation | Complexity |
+|-----------|------------|
+| Insert | O(log n) |
+| Get smallest element | O(1) |
+| Get largest element | O(1) |
+| Remove smallest element | O(log n) |
+| Remove largest element | O(log n) |
+
+In all of the above, `n` is the number of elements in the heap.
+
+
+
+The above graph was generated in release mode on a MacBook Pro (16-inch, 2019) with a 2.3 GHz 8-Core Intel Core i9 using the benchmarks defined in the `swift-collections-benchmark` target.
+
+## Implementation Details
+
+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).
+
+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.
+
+["A min-max heap is a complete binary tree data structure."](https://en.wikipedia.org/wiki/Min-max_heap) This means that all the levels in the tree are filled except the last and that they are filled from left to right. The tree can be stored in an array:
+
+```
+// Min-max heap:
+level 0: 8
+level 1: 71 41
+level 2: 31 10 11 16
+level 3: 46 51 31 21 13
+
+// Array representation:
+[8, 71, 41, 31, 10, 11, 16, 46, 51, 31, 21, 13]
+```
+
+**Heap property**: Each element in an even level in the tree is less than all its descendants; each element in an odd level in the tree is greater than all its descendants. _Mutations to the heap **must** maintain this heap property._
+
+The levels start at 0 (even), so the smallest element in the tree is at the root. In the example above, the root of the tree is 8, which is the smallest element. The next level in the tree (containing 71 and 41) is a max level, so those elements are greater than all their respective descendants. Because this is the first max level in the tree, the largest element in the tree is one of the two elements (71).
+
+Note that the comparisons only take into account descendants — it is possible, for example, for elements at a lower level to be larger than elements in a different branch that are higher up the tree. In the example above, 41 isn't the second-largest element in the tree, but _it is_ the largest element in the right branch of the root node.
+
+---
+
+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.
diff --git a/Documentation/Images/Heap Performance.png b/Documentation/Images/Heap Performance.png
new file mode 100644
index 00000000..544474b1
Binary files /dev/null and b/Documentation/Images/Heap Performance.png differ
diff --git a/Package.swift b/Package.swift
index d5825439..538f2d8a 100644
--- a/Package.swift
+++ b/Package.swift
@@ -54,6 +54,7 @@ let package = Package(
.library(name: "Collections", targets: ["Collections"]),
.library(name: "DequeModule", targets: ["DequeModule"]),
.library(name: "OrderedCollections", targets: ["OrderedCollections"]),
+ .library(name: "PriorityQueueModule", targets: ["PriorityQueueModule"]),
],
dependencies: [
// This is only used in the benchmark executable target.
@@ -65,6 +66,7 @@ let package = Package(
dependencies: [
"DequeModule",
"OrderedCollections",
+ "PriorityQueueModule",
],
path: "Sources/Collections",
exclude: ["CMakeLists.txt"],
@@ -130,6 +132,16 @@ let package = Package(
name: "OrderedCollectionsTests",
dependencies: ["OrderedCollections", "CollectionsTestSupport"],
swiftSettings: settings),
+
+ // PriorityQueue
+ .target(
+ name: "PriorityQueueModule",
+ exclude: ["CMakeLists.txt"],
+ swiftSettings: settings),
+ .testTarget(
+ name: "PriorityQueueTests",
+ dependencies: ["PriorityQueueModule"],
+ swiftSettings: settings),
],
cxxLanguageStandard: .cxx1z
)
diff --git a/README.md b/README.md
index 4f1d72a1..1ef75646 100644
--- a/README.md
+++ b/README.md
@@ -16,6 +16,8 @@ The package currently provides the following implementations:
- [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits.
+- [`Heap`](Documentation/Heap.md], a min-max heap backed by an array.
+
[Deque]: Documentation/Deque.md
[OrderedSet]: Documentation/OrderedSet.md
[OrderedDictionary]: Documentation/OrderedDictionary.md
@@ -224,4 +226,3 @@ Like all Swift.org projects, we would like the Swift Collections project to fost
The current code owner of this package is Karoy Lorentey ([@lorentey](https://github.com/lorentey)). You can contact him [on the Swift forums](https://forums.swift.org/u/lorentey/summary), or by writing an email to klorentey at apple dot com. (Please keep it related to this project.)
In case of moderation issues, you can also directly contact a member of the [Swift Core Team](https://swift.org/community/#community-structure).
-
diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt
index fa125f86..42a06958 100644
--- a/Sources/CMakeLists.txt
+++ b/Sources/CMakeLists.txt
@@ -10,3 +10,4 @@ See https://swift.org/LICENSE.txt for license information
add_subdirectory(Collections)
add_subdirectory(DequeModule)
add_subdirectory(OrderedCollections)
+add_subdirectory(PriorityQueueModule)
diff --git a/Sources/Collections/CMakeLists.txt b/Sources/Collections/CMakeLists.txt
index aadba16a..ae7b6cca 100644
--- a/Sources/Collections/CMakeLists.txt
+++ b/Sources/Collections/CMakeLists.txt
@@ -11,7 +11,8 @@ add_library(Collections
Collections.swift)
target_link_libraries(Collections PRIVATE
DequeModule
- OrderedCollections)
+ OrderedCollections
+ PriorityQueueModule)
set_target_properties(Collections PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
diff --git a/Sources/Collections/Collections.swift b/Sources/Collections/Collections.swift
index 525b3428..beacfc23 100644
--- a/Sources/Collections/Collections.swift
+++ b/Sources/Collections/Collections.swift
@@ -11,3 +11,4 @@
@_exported import DequeModule
@_exported import OrderedCollections
+@_exported import PriorityQueueModule
diff --git a/Sources/PriorityQueueModule/CMakeLists.txt b/Sources/PriorityQueueModule/CMakeLists.txt
new file mode 100644
index 00000000..1ddcd8e2
--- /dev/null
+++ b/Sources/PriorityQueueModule/CMakeLists.txt
@@ -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)
diff --git a/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift b/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift
new file mode 100644
index 00000000..466d6c94
--- /dev/null
+++ b/Sources/PriorityQueueModule/Heap+ExpressibleByArrayLiteral.swift
@@ -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)
+ }
+}
diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift
new file mode 100644
index 00000000..3396df5a
--- /dev/null
+++ b/Sources/PriorityQueueModule/Heap+Invariants.swift
@@ -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
+}
diff --git a/Sources/PriorityQueueModule/Heap+OrderedViews.swift b/Sources/PriorityQueueModule/Heap+OrderedViews.swift
new file mode 100644
index 00000000..bf6536c8
--- /dev/null
+++ b/Sources/PriorityQueueModule/Heap+OrderedViews.swift
@@ -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)
+ }
+}
diff --git a/Sources/PriorityQueueModule/Heap.swift b/Sources/PriorityQueueModule/Heap.swift
new file mode 100644
index 00000000..c04e90e4
--- /dev/null
+++ b/Sources/PriorityQueueModule/Heap.swift
@@ -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 {
+ @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(_ 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(contentsOf newElements: S) where S.Element == Element {
+ for element in newElements {
+ insert(element)
+ }
+ }
+}
diff --git a/Tests/PriorityQueueTests/HeapTests.swift b/Tests/PriorityQueueTests/HeapTests.swift
new file mode 100644
index 00000000..12b6b03b
--- /dev/null
+++ b/Tests/PriorityQueueTests/HeapTests.swift
@@ -0,0 +1,426 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 XCTest
+@testable import PriorityQueueModule
+
+final class HeapTests: XCTestCase {
+ func test_isEmpty() {
+ var heap = Heap()
+ XCTAssertTrue(heap.isEmpty)
+
+ heap.insert(42)
+ XCTAssertFalse(heap.isEmpty)
+
+ let _ = heap.popMin()
+ XCTAssertTrue(heap.isEmpty)
+ }
+
+ func test_count() {
+ var heap = Heap()
+ XCTAssertEqual(heap.count, 0)
+
+ heap.insert(20)
+ XCTAssertEqual(heap.count, 1)
+
+ heap.insert(40)
+ XCTAssertEqual(heap.count, 2)
+
+ _ = heap.popMin()
+ XCTAssertEqual(heap.count, 1)
+ }
+
+ func test_unordered() {
+ let heap = Heap((1...10))
+ XCTAssertEqual(Set(heap.unordered), Set(1...10))
+ }
+
+ struct Task: Comparable {
+ let name: String
+ let priority: Int
+
+ static func < (lhs: Task, rhs: Task) -> Bool {
+ lhs.priority < rhs.priority
+ }
+ }
+
+ func test_insert() {
+ var heap = Heap()
+
+ XCTAssertEqual(heap.count, 0)
+ heap.insert(Task(name: "Hello, world", priority: 50))
+ XCTAssertEqual(heap.count, 1)
+ }
+
+ func test_insert_contentsOf() {
+ var heap = Heap()
+ heap.insert(contentsOf: (1...10).shuffled())
+ XCTAssertEqual(heap.count, 10)
+ XCTAssertEqual(heap.popMax(), 10)
+ XCTAssertEqual(heap.popMin(), 1)
+
+ heap.insert(contentsOf: (21...50).shuffled())
+ XCTAssertEqual(heap.count, 38)
+ XCTAssertEqual(heap.max(), 50)
+ XCTAssertEqual(heap.min(), 2)
+
+ heap.insert(contentsOf: [-10, -9, -8, -7, -6, -5].shuffled())
+ XCTAssertEqual(heap.count, 44)
+ XCTAssertEqual(heap.min(), -10)
+ }
+
+ func test_insert_contentsOf_withSequenceFunction() {
+ func addTwo(_ i: Int) -> Int {
+ i + 2
+ }
+
+ let evens = sequence(first: 0, next: addTwo(_:)).prefix(20)
+ var heap = Heap(evens)
+ XCTAssertEqual(heap.count, 20)
+
+ heap.insert(contentsOf: sequence(first: 1, next: addTwo(_:)).prefix(20))
+ XCTAssertEqual(heap.count, 40)
+
+ for (idx, i) in heap.ascending.enumerated() {
+ XCTAssertEqual(idx, i)
+ }
+ }
+
+ func test_min() {
+ var heap = Heap()
+ XCTAssertNil(heap.min())
+
+ heap.insert(5)
+ XCTAssertEqual(5, heap.min())
+
+ heap.insert(12)
+ XCTAssertEqual(5, heap.min())
+
+ heap.insert(2)
+ XCTAssertEqual(2, heap.min())
+
+ heap.insert(1)
+ XCTAssertEqual(1, heap.min())
+ }
+
+ func test_max() {
+ var heap = Heap()
+ XCTAssertNil(heap.max())
+
+ heap.insert(42)
+ XCTAssertEqual(42, heap.max())
+
+ heap.insert(20)
+ XCTAssertEqual(42, heap.max())
+
+ heap.insert(63)
+ XCTAssertEqual(63, heap.max())
+
+ heap.insert(90)
+ XCTAssertEqual(90, heap.max())
+ }
+
+ func test_popMin() {
+ var heap = Heap()
+ XCTAssertNil(heap.popMin())
+
+ heap.insert(7)
+ XCTAssertEqual(heap.popMin(), 7)
+
+ heap.insert(12)
+ heap.insert(9)
+ XCTAssertEqual(heap.popMin(), 9)
+
+ heap.insert(13)
+ heap.insert(1)
+ heap.insert(4)
+ XCTAssertEqual(heap.popMin(), 1)
+
+ for i in (1...20).shuffled() {
+ heap.insert(i)
+ }
+
+ XCTAssertEqual(heap.popMin(), 1)
+ XCTAssertEqual(heap.popMin(), 2)
+ XCTAssertEqual(heap.popMin(), 3)
+ XCTAssertEqual(heap.popMin(), 4)
+ XCTAssertEqual(heap.popMin(), 4) // One 4 was still in the heap from before
+ XCTAssertEqual(heap.popMin(), 5)
+ XCTAssertEqual(heap.popMin(), 6)
+ XCTAssertEqual(heap.popMin(), 7)
+ XCTAssertEqual(heap.popMin(), 8)
+ XCTAssertEqual(heap.popMin(), 9)
+ XCTAssertEqual(heap.popMin(), 10)
+ XCTAssertEqual(heap.popMin(), 11)
+ XCTAssertEqual(heap.popMin(), 12)
+ XCTAssertEqual(heap.popMin(), 12) // One 12 was still in the heap from before
+ XCTAssertEqual(heap.popMin(), 13)
+ XCTAssertEqual(heap.popMin(), 13) // One 13 was still in the heap from before
+ XCTAssertEqual(heap.popMin(), 14)
+ XCTAssertEqual(heap.popMin(), 15)
+ XCTAssertEqual(heap.popMin(), 16)
+ XCTAssertEqual(heap.popMin(), 17)
+ XCTAssertEqual(heap.popMin(), 18)
+ XCTAssertEqual(heap.popMin(), 19)
+ XCTAssertEqual(heap.popMin(), 20)
+
+ XCTAssertNil(heap.popMin())
+ }
+
+ func test_popMax() {
+ var heap = Heap()
+ XCTAssertNil(heap.popMax())
+
+ heap.insert(7)
+ XCTAssertEqual(heap.popMax(), 7)
+
+ heap.insert(12)
+ heap.insert(9)
+ XCTAssertEqual(heap.popMax(), 12)
+
+ heap.insert(13)
+ heap.insert(1)
+ heap.insert(4)
+ XCTAssertEqual(heap.popMax(), 13)
+
+ for i in (1...20).shuffled() {
+ heap.insert(i)
+ }
+
+ XCTAssertEqual(heap.popMax(), 20)
+ XCTAssertEqual(heap.popMax(), 19)
+ XCTAssertEqual(heap.popMax(), 18)
+ XCTAssertEqual(heap.popMax(), 17)
+ XCTAssertEqual(heap.popMax(), 16)
+ XCTAssertEqual(heap.popMax(), 15)
+ XCTAssertEqual(heap.popMax(), 14)
+ XCTAssertEqual(heap.popMax(), 13)
+ XCTAssertEqual(heap.popMax(), 12)
+ XCTAssertEqual(heap.popMax(), 11)
+ XCTAssertEqual(heap.popMax(), 10)
+ XCTAssertEqual(heap.popMax(), 9)
+ XCTAssertEqual(heap.popMax(), 9) // One 9 was still in the heap from before
+ XCTAssertEqual(heap.popMax(), 8)
+ XCTAssertEqual(heap.popMax(), 7)
+ XCTAssertEqual(heap.popMax(), 6)
+ XCTAssertEqual(heap.popMax(), 5)
+ XCTAssertEqual(heap.popMax(), 4)
+ XCTAssertEqual(heap.popMax(), 4) // One 4 was still in the heap from before
+ XCTAssertEqual(heap.popMax(), 3)
+ XCTAssertEqual(heap.popMax(), 2)
+ XCTAssertEqual(heap.popMax(), 1)
+ XCTAssertEqual(heap.popMax(), 1) // One 1 was still in the heap from before
+
+ XCTAssertNil(heap.popMax())
+ }
+
+ func test_removeMin() {
+ var heap = Heap((1...20).shuffled())
+
+ XCTAssertEqual(heap.removeMin(), 1)
+ XCTAssertEqual(heap.removeMin(), 2)
+ XCTAssertEqual(heap.removeMin(), 3)
+ XCTAssertEqual(heap.removeMin(), 4)
+ XCTAssertEqual(heap.removeMin(), 5)
+ XCTAssertEqual(heap.removeMin(), 6)
+ XCTAssertEqual(heap.removeMin(), 7)
+ XCTAssertEqual(heap.removeMin(), 8)
+ XCTAssertEqual(heap.removeMin(), 9)
+ XCTAssertEqual(heap.removeMin(), 10)
+ XCTAssertEqual(heap.removeMin(), 11)
+ XCTAssertEqual(heap.removeMin(), 12)
+ XCTAssertEqual(heap.removeMin(), 13)
+ XCTAssertEqual(heap.removeMin(), 14)
+ XCTAssertEqual(heap.removeMin(), 15)
+ XCTAssertEqual(heap.removeMin(), 16)
+ XCTAssertEqual(heap.removeMin(), 17)
+ XCTAssertEqual(heap.removeMin(), 18)
+ XCTAssertEqual(heap.removeMin(), 19)
+ XCTAssertEqual(heap.removeMin(), 20)
+ }
+
+ func test_removeMax() {
+ var heap = Heap((1...20).shuffled())
+
+ XCTAssertEqual(heap.removeMax(), 20)
+ XCTAssertEqual(heap.removeMax(), 19)
+ XCTAssertEqual(heap.removeMax(), 18)
+ XCTAssertEqual(heap.removeMax(), 17)
+ XCTAssertEqual(heap.removeMax(), 16)
+ XCTAssertEqual(heap.removeMax(), 15)
+ XCTAssertEqual(heap.removeMax(), 14)
+ XCTAssertEqual(heap.removeMax(), 13)
+ XCTAssertEqual(heap.removeMax(), 12)
+ XCTAssertEqual(heap.removeMax(), 11)
+ XCTAssertEqual(heap.removeMax(), 10)
+ XCTAssertEqual(heap.removeMax(), 9)
+ XCTAssertEqual(heap.removeMax(), 8)
+ XCTAssertEqual(heap.removeMax(), 7)
+ XCTAssertEqual(heap.removeMax(), 6)
+ XCTAssertEqual(heap.removeMax(), 5)
+ XCTAssertEqual(heap.removeMax(), 4)
+ XCTAssertEqual(heap.removeMax(), 3)
+ XCTAssertEqual(heap.removeMax(), 2)
+ XCTAssertEqual(heap.removeMax(), 1)
+ }
+
+ // MARK: -
+
+ func test_min_struct() {
+ var heap = Heap()
+ XCTAssertNil(heap.min())
+
+ let firstTask = Task(name: "Do something", priority: 10)
+ heap.insert(firstTask)
+ XCTAssertEqual(heap.min(), firstTask)
+
+ let higherPriorityTask = Task(name: "Urgent", priority: 100)
+ heap.insert(higherPriorityTask)
+ XCTAssertEqual(heap.min(), firstTask)
+
+ let lowerPriorityTask = Task(name: "Get this done today", priority: 1)
+ heap.insert(lowerPriorityTask)
+ XCTAssertEqual(heap.min(), lowerPriorityTask)
+ }
+
+ func test_max_struct() {
+ var heap = Heap()
+ XCTAssertNil(heap.max())
+
+ let firstTask = Task(name: "Do something", priority: 10)
+ heap.insert(firstTask)
+ XCTAssertEqual(heap.max(), firstTask)
+
+ let lowerPriorityTask = Task(name: "Get this done today", priority: 1)
+ heap.insert(lowerPriorityTask)
+ XCTAssertEqual(heap.max(), firstTask)
+
+ let higherPriorityTask = Task(name: "Urgent", priority: 100)
+ heap.insert(higherPriorityTask)
+ XCTAssertEqual(heap.max(), higherPriorityTask)
+ }
+
+ func test_popMin_struct() {
+ var heap = Heap()
+ XCTAssertNil(heap.popMin())
+
+ let lowPriorityTask = Task(name: "Do something when you have time", priority: 1)
+ heap.insert(lowPriorityTask)
+
+ let highPriorityTask = Task(name: "Get this done today", priority: 50)
+ heap.insert(highPriorityTask)
+
+ let urgentTask = Task(name: "Urgent", priority: 100)
+ heap.insert(urgentTask)
+
+ XCTAssertEqual(heap.popMin(), lowPriorityTask)
+ XCTAssertEqual(heap.popMin(), highPriorityTask)
+ XCTAssertEqual(heap.popMin(), urgentTask)
+ XCTAssertNil(heap.popMin())
+ }
+
+ func test_popMax_struct() {
+ var heap = Heap()
+ XCTAssertNil(heap.popMax())
+
+ let lowPriorityTask = Task(name: "Do something when you have time", priority: 1)
+ heap.insert(lowPriorityTask)
+
+ let highPriorityTask = Task(name: "Get this done today", priority: 50)
+ heap.insert(highPriorityTask)
+
+ let urgentTask = Task(name: "Urgent", priority: 100)
+ heap.insert(urgentTask)
+
+ XCTAssertEqual(heap.popMax(), urgentTask)
+ XCTAssertEqual(heap.popMax(), highPriorityTask)
+ XCTAssertEqual(heap.popMax(), lowPriorityTask)
+ XCTAssertNil(heap.popMax())
+ }
+
+ // MARK: -
+
+ func test_levelCalculation() {
+ // Check alternating min and max levels in the heap
+ let q = Heap()
+ var isMin = true
+ for exp in 0...12 {
+ // Check [2^exp, 2^(exp + 1))
+ for i in Int(pow(2, Double(exp)) - 1)..((0...50).shuffled())
+
+ var increment = 0
+ for val in heap.ascending {
+ XCTAssertEqual(increment, val)
+ increment += 1
+ }
+
+ increment = 50
+ for val in heap.descending {
+ XCTAssertEqual(increment, val)
+ increment -= 1
+ }
+ }
+}