Minimum and maximum in Kotlin

To find the minimum and maximum elements in an array, you can iterate over the array and keep track of the minimum and maximum elements you’ve seen so far. Here’s an example implementation in Kotlin.

Kotlin
fun findMinMax(arr: IntArray): Pair<Int, Int>? {
    val n = arr.size
    if (n == 0) {
        return null
    }
    var minElem = arr[0]
    var maxElem = arr[0]
    for (i in 1 until n) {
        if (arr[i] < minElem) {
            minElem = arr[i]
        }
        if (arr[i] > maxElem) {
            maxElem = arr[i]
        }
    }
    return Pair(minElem, maxElem)
}

findMinMax takes an IntArray as input and returns a nullable Pair<Int, Int> containing the minimum and maximum elements. The function first gets the length of the array n. If the length is 0, the function returns null. Otherwise, it initializes the minElem and maxElem variables to the first element of the array. The for loop iterates over the rest of the array and updates minElem and maxElem if a smaller or larger element is found. Finally, the function returns a Pair containing the minimum and maximum elements.

Kotlin
fun findMinMax(arr: IntArray): Pair<Int, Int>? {
    val n = arr.size
    if (n == 0) {
        return null
    }
    var minElem = arr[0]
    var maxElem = arr[0]
    for (i in 1 until n) {
        if (arr[i] < minElem) {
            minElem = arr[i]
        }
        if (arr[i] > maxElem) {
            maxElem = arr[i]
        }
    }
    return Pair(minElem, maxElem)
}
fun main(){
    val arr = intArrayOf(1, 2, 3, 4, 5)
	val minMax = findMinMax(arr)
	if (minMax != null) {
    	val (min, max) = minMax
    	println("Minimum element: $min")
    	println("Maximum element: $max")
	} else {
    	println("Array is empty")
	}
}

this will result a output :

Minimum element: 1

Maximum element: 5

Leave a Comment