Skip to content

Commit e15e133

Browse files
authored
switch from removeFirst to stride for pairing
We don't need to alter a local copy of `array` to generate each pair, instead use stride(from:to:by). In my simple [tests](https://gist.github.com/TheIronBorn/cc0507b36fddad291aa34674eb52ad8f), this can be up to an order of magnitude faster.
1 parent 5e7fc54 commit e15e133

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

Select Minimum Maximum/MinimumMaximumPairs.swift

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,18 @@
33
*/
44

55
func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? {
6-
var array = array
76
guard !array.isEmpty else {
87
return nil
98
}
109

1110
var minimum = array.first!
1211
var maximum = array.first!
1312

13+
// if 'array' has an odd number of items, let 'minimum' or 'maximum' deal with the leftover
1414
let hasOddNumberOfItems = array.count % 2 != 0
15-
if hasOddNumberOfItems {
16-
array.removeFirst()
17-
}
18-
19-
while !array.isEmpty {
20-
let pair = (array.removeFirst(), array.removeFirst())
15+
let start = hasOddNumberOfItems ? 1 : 0
16+
for i in stride(from: start, to: array.count, by: 2) {
17+
let pair = (array[i], array[i+1])
2118

2219
if pair.0 > pair.1 {
2320
if pair.0 > maximum {
@@ -35,6 +32,6 @@ func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? {
3532
}
3633
}
3734
}
38-
35+
3936
return (minimum, maximum)
4037
}

0 commit comments

Comments
 (0)