# andyRon/swift-algorithm-club-cn

Switch branches/tags
Nothing to show
Fetching latest commit…
Cannot retrieve the latest commit at this time.

# 查找最大／最小值(Select Minimum / Maximum)

## 最大值或最小值

### 代码

```func minimum<T: Comparable>(_ array: [T]) -> T? {
guard var minimum = array.first else {
return nil
}

for element in array.dropFirst() {
minimum = element < minimum ? element : minimum
}
return minimum
}

func maximum<T: Comparable>(_ array: [T]) -> T? {
guard var maximum = array.first else {
return nil
}

for element in array.dropFirst() {
maximum = element > maximum ? element : maximum
}
return maximum
}```

```let array = [ 8, 3, 9, 4, 6 ]
minimum(array)   // This will return 3
maximum(array)   // This will return 9```

### Swift的标准库

Swift库已经包含一个叫做`SequenceType`的扩展，它可返回序列中的最小/最大元素。

```let array = [ 8, 3, 9, 4, 6 ]
array.minElement()   // This will return 3
array.maxElement()   // This will return 9```
```let array = [ 8, 3, 9, 4, 6 ]
//swift3
array.min()   // This will return 3
array.max()   // This will return 9```

## 最大值和最小值

### 代码

```func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? {
guard var minimum = array.first else {
return nil
}
var maximum = minimum

// if 'array' has an odd number of items, let 'minimum' or 'maximum' deal with the leftover
let start = array.count % 2 // 1 if odd, skipping the first element
for i in stride(from: start, to: array.count, by: 2) {
let pair = (array[i], array[i+1])

if pair.0 > pair.1 {
if pair.0 > maximum {
maximum = pair.0
}
if pair.1 < minimum {
minimum = pair.1
}
} else {
if pair.1 > maximum {
maximum = pair.1
}
if pair.0 < minimum {
minimum = pair.0
}
}
}

return (minimum, maximum)
}```

```let result = minimumMaximum(array)!
result.minimum   // This will return 3
result.maximum   // This will return 9```