Search code examples
iosarraysswiftalgorithmnumbers

iOS - selecting second lowest number in integer array


Let's say I have an array of numbers:

let numbers: [Int] = [1,2,3,4,5,6,7,8]

I want to pick out the second lowest number in that array but I don't want to use an index, I know you can pick the lowest and highest integer using min/maxElement dot notation so how would I get the second lowest or the second highest?


Solution

  • A direct implementation: (as Sulthan suggested?)

    func secondMax(numbers: [Int]) -> Int {
        let (_, second) = numbers.reduce((Int.min, Int.min)) {(max2: (first: Int, second: Int), value: Int) in
            if value > max2.first {
                return (value, max2.first)
            } else if value > max2.second {
                return (max2.first, value)
            } else {
                return max2
            }
        }
        return second
    }
    print(secondMax([1,2,3,4,5,6,7,8])) //->7
    print(secondMax([1,1,2,3,4,4])) //->4
    print(secondMax([5,5,6,1,2,3,4])) //->5
    print(secondMax([5,6,6,1,2,3,4])) //->6