How to Find Min Max in Array

[Question] Find Maximum and minimum of an array in swift using minimum number of comparisons

func findMinMax(inputArray: [Int]) -> (min:Int, max: Int) {
    if inputArray.count == 0 { return (min:-1, max: -1) }
    var minNumber = inputArray[0]
    var maxNumber = inputArray[0]
    for index in 1..<inputArray.count {
        if inputArray[index] < minNumber {
            minNumber = inputArray[index]
        }
        if inputArray[index] > maxNumber {
            maxNumber = inputArray[index]
        }
    }
    return (min: minNumber, max: maxNumber)
}
#Approach: 1

Use first element as min max & start loop from second element onwards & return tuple of the min max number

Leave a Comment

Your email address will not be published. Required fields are marked *