Skip to content

Commit 19c1d00

Browse files
authored
Remove the last element before determining the insertion index (#173)
This could result in fewer comparisons. Additionally, it ensures that the insertion index is valid for insertion. The `removeLast()` documentation states: > Calling this method may invalidate all saved indices of this collection. Do not rely on a previously stored index value after altering a collection with any operation that can change its length.
1 parent e2fa131 commit 19c1d00

File tree

1 file changed

+1
-3
lines changed

1 file changed

+1
-3
lines changed

Sources/Algorithms/MinMax.swift

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,9 @@ extension Sequence {
2828
while let e = iterator.next() {
2929
// To be part of `result`, `e` must be strictly less than `result.last`.
3030
guard try areInIncreasingOrder(e, result.last!) else { continue }
31+
result.removeLast()
3132
let insertionIndex =
3233
try result.partitioningIndex { try areInIncreasingOrder(e, $0) }
33-
34-
assert(insertionIndex != result.endIndex)
35-
result.removeLast()
3634
result.insert(e, at: insertionIndex)
3735
}
3836

0 commit comments

Comments
 (0)