Skip to content

Commit fe478b7

Browse files
[stdlib] Add sort stability comment to min()/max()
1 parent 75a6609 commit fe478b7

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

stdlib/public/core/Algorithm.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,13 +46,18 @@ public func find<
4646
/// Returns the lesser of `x` and `y`.
4747
@warn_unused_result
4848
public func min<T : Comparable>(x: T, _ y: T) -> T {
49+
// In case `x == y` we pick `x`.
50+
// This preserves any pre-existing order in case `T` has identity,
51+
// which is important for e.g. the stability of sorting algorithms.
52+
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
4953
return y < x ? y : x
5054
}
5155

5256
/// Returns the least argument passed.
5357
@warn_unused_result
5458
public func min<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
5559
var minValue = min(min(x, y), z)
60+
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
5661
for value in rest where value < minValue {
5762
minValue = value
5863
}
@@ -62,13 +67,15 @@ public func min<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
6267
/// Returns the greater of `x` and `y`.
6368
@warn_unused_result
6469
public func max<T : Comparable>(x: T, _ y: T) -> T {
70+
// In case `x == y`, we pick `y`. See min(_:_:).
6571
return y >= x ? y : x
6672
}
6773

6874
/// Returns the greatest argument passed.
6975
@warn_unused_result
7076
public func max<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
7177
var maxValue = max(max(x, y), z)
78+
// In case `value == maxValue`, we pick `value`. See min(_:_:).
7279
for value in rest where value >= maxValue {
7380
maxValue = value
7481
}

0 commit comments

Comments
 (0)