Finding the Minimum and Maximum Values in a Kotlin Array

Introduces how to find the minimum and maximum values among the elements of an array.

Using minOrNull() and maxOrNull()

The minOrNull() and maxOrNull() functions provided by Array return the minimum and maximum values of an array.

fun main() {
    val array = arrayOf(66, 10, 34, 70, 42)

    println("min: ${array.minOrNull()}")
    println("max: ${array.maxOrNull()}")
}

Output:

min: 10
max: 70

Using Sorting

The Array.sorted() function returns an array sorted in ascending order.

Because it is sorted in ascending order, the first element by index is the minimum value and the last element is the maximum value.

fun main() {
    val array = arrayOf(66, 10, 34, 70, 42)

    val sortedArray = array.sorted()

    println("min: ${sortedArray.first()}")
    println("max: ${sortedArray.last()}")
}

Output:

min: 10
max: 70

Using a Loop

You can also find the minimum and maximum values by iterating over every element of the array with a for loop.

As shown below, assign the maximum value of Int as the initial value of the min variable and the minimum value of Int as the initial value of the max variable, then find the values while iterating with a for loop.

fun main() {
    val array = arrayOf(66, 10, 34, 70, 42)

    var max = Int.MIN_VALUE
    var min = Int.MAX_VALUE
    for (i in array) {
        min = if (min > i) i else min
        max = if (max < i) i else max
    }

    println("min: $min")
    println("max: $max")
}

Output:

min: 10
max: 70