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

Xiith is created for educational, experimental, and schooling purpose. Examples on Xiith are made easier to make a better or basic understanding. Tutorials, testimonials, and examples are continuously checked to avoid delusion, but we cannot take complete responsibility of all programs on Xiith. When you are operating this site, you have to agree to read and accept our terms of use, cookie and privacy policy.Copyright © 2020 by Xiith. All Rights Reserved. About us.