Merge pull request #455 from DakshinD/heap-max-func

Align Heap._UnsafeHandle min/maxValue tie-breaking with Swift.min/max
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2025-05-15 21:08:49 -07:00
commit ace6afa65b
3 files changed
+62 -3

No files matched your search

+7 -2
View File
@@ -81,12 +81,17 @@ extension Heap._UnsafeHandle {
@inlinable @inline(__always)
internal func minValue(_ a: _HeapNode, _ b: _HeapNode) -> _HeapNode {
self[a] < self[b] ? a : b
// The expression used here matches the implementation of the
// standard `Swift.min(_:_:)` function. This attempts to
// preserve any pre-existing order in case `T` has identity.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
self[b] < self[a] ? b : a
}
@inlinable @inline(__always)
internal func maxValue(_ a: _HeapNode, _ b: _HeapNode) -> _HeapNode {
self[a] < self[b] ? b : a
// In case `a` and `b` match, we need to pick `b`. See `minValue(_:_:)`.
self[b] >= self[a] ? b : a
}
}
+1 -1
View File
@@ -212,7 +212,7 @@ extension Heap {
handle.swapAt(.leftMax, with: &removed)
}
} else {
let maxNode = handle.maxValue(.rightMax, .leftMax)
let maxNode = handle.maxValue(.leftMax, .rightMax)
handle.swapAt(maxNode, with: &removed)
handle.trickleDownMax(maxNode)
}
+54
View File
@@ -587,4 +587,58 @@ final class HeapTests: CollectionTestCase {
}
}
}
struct Distinguishable: Comparable, CustomStringConvertible {
var value: Int
var id: Int
static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
var description: String { "\(value)/\(id)" }
}
func test_tieBreaks_min() {
var heap: Heap = [
Distinguishable(value: 1, id: 1),
Distinguishable(value: 1, id: 2),
Distinguishable(value: 1, id: 3),
Distinguishable(value: 1, id: 4),
Distinguishable(value: 1, id: 5),
]
while !heap.isEmpty {
let oldID = heap.min!.id
let newID = 10 * oldID
let old = heap.replaceMin(with: Distinguishable(value: 1, id: newID))
expectEqual(old.id, oldID)
expectEqual(heap.min?.id, 10 * oldID)
expectNotNil(heap.removeMin()) { min in
expectEqual(min.id, newID)
}
}
}
func test_tieBreaks_max() {
var heap: Heap = [
Distinguishable(value: 1, id: 1),
Distinguishable(value: 1, id: 2),
Distinguishable(value: 1, id: 3),
Distinguishable(value: 1, id: 4),
Distinguishable(value: 1, id: 5),
]
while !heap.isEmpty {
let oldID = heap.max!.id
let newID = 10 * oldID
print(heap.unordered)
let old = heap.replaceMax(with: Distinguishable(value: 1, id: newID))
expectEqual(old.id, oldID)
expectEqual(heap.max?.id, 10 * oldID)
expectNotNil(heap.removeMax()) { max in
expectEqual(max.id, newID)
}
}
}
}