@@ -44,47 +44,50 @@ public func find<
44
44
}
45
45
46
46
/// Returns the lesser of `x` and `y`.
47
+ ///
48
+ /// If `x == y`, returns `x`.
47
49
@warn_unused_result
48
50
public func min< T : Comparable > ( x: T , _ y: T ) -> T {
49
- var r = x
50
- if y < x {
51
- r = y
52
- }
53
- return r
51
+ // In case `x == y` we pick `x`.
52
+ // This preserves any pre-existing order in case `T` has identity,
53
+ // which is important for e.g. the stability of sorting algorithms.
54
+ // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
55
+ return y < x ? y : x
54
56
}
55
57
56
58
/// Returns the least argument passed.
59
+ ///
60
+ /// If there are multiple equal least arguments, returns the first one.
57
61
@warn_unused_result
58
62
public func min< T : Comparable > ( x: T , _ y: T , _ z: T , _ rest: T ... ) -> T {
59
- var r = x
60
- if y < x {
61
- r = y
62
- }
63
- if z < r {
64
- r = z
63
+ var minValue = min ( min ( x, y) , z)
64
+ // In case `value == minValue`, we pick `minValue`. See min(_:_:).
65
+ for value in rest where value < minValue {
66
+ minValue = value
65
67
}
66
- for t in rest {
67
- if t < r {
68
- r = t
69
- }
70
- }
71
- return r
68
+ return minValue
72
69
}
73
70
74
71
/// Returns the greater of `x` and `y`.
72
+ ///
73
+ /// If `x == y`, returns `y`.
75
74
@warn_unused_result
76
75
public func max< T : Comparable > ( x: T , _ y: T ) -> T {
76
+ // In case `x == y`, we pick `y`. See min(_:_:).
77
77
return y >= x ? y : x
78
78
}
79
79
80
80
/// Returns the greatest argument passed.
81
+ ///
82
+ /// If there are multiple equal greatest arguments, returns the last one.
81
83
@warn_unused_result
82
84
public func max< T : Comparable > ( x: T , _ y: T , _ z: T , _ rest: T ... ) -> T {
83
- var r = max ( max ( x, y) , z)
84
- for t in rest where t >= r {
85
- r = t
85
+ var maxValue = max ( max ( x, y) , z)
86
+ // In case `value == maxValue`, we pick `value`. See min(_:_:).
87
+ for value in rest where value >= maxValue {
88
+ maxValue = value
86
89
}
87
- return r
90
+ return maxValue
88
91
}
89
92
90
93
/// Returns the result of slicing `elements` into sub-sequences that
0 commit comments