Kotlin Program to sort an array in ascending order


In this program, You will learn how to sort an array in ascending order in Kotlin.


Array list are: 3 4 5 61 9 7

After sorting:3 4 5 7 9 61

Example: How to sort an array in ascending order in Kotlin.

import java.util.Scanner

fun main(args: Array<String>) {

    val arr = IntArray(6)
    var temp: Int
    val sc = Scanner(System.`in`)

    print("Enter 6 elements:")

    for (i in 0 until arr.size) {
        arr[i] = sc.nextInt()
    }

    for (i in 0 until arr.size) {
        for (j in i + 1 until arr.size) {
            if (arr[i] > arr[j]) {
                temp = arr[i]
                arr[i] = arr[j]
                arr[j] = temp
            }
        }
    }

    print("Array list after sorting:")
    for (n in arr) {
        print("$n ")
    }
}

Output:

Enter 6 elements:20 10 30 40 60 50
Array list after sorting:10 20 30 40 50 60