Created
January 3, 2017 01:36
-
-
Save ChenCodes/3fab95d8971f8d086dc45abe1ebe3e9d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func minimumMaximum<T: Comparable>(_ array: [T]) -> (minimum: T, maximum: T)? { | |
var array = array | |
guard !array.isEmpty else { | |
return nil | |
} | |
var minimum = array.first! | |
var maximum = array.first! | |
let hasOddNumberOfItems = array.count % 2 != 0 | |
if hasOddNumberOfItems { | |
array.removeFirst() | |
} | |
while !array.isEmpty { | |
let pair = (array.removeFirst(), array.removeFirst()) | |
if pair.0 > pair.1 { //if the first number if greater than the second number | |
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 array = [ 8, 3, 9, 4, 6 ] | |
let result = minimumMaximum(array)! | |
print(result.minimum) // This will return 3 | |
print(result.maximum) // This will return 9 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment