Home »
Kotlin »
Kotlin programs »
Kotlin array programs
Kotlin program to sort an array in ascending order
Kotlin | Sorting an array (Ascending Order): Here, we are going to learn how to sort an array in ascending order in Kotlin programming language?
Submitted by IncludeHelp, on May 03, 2020
Given an array, we have to sort its elements in ascending order.
Example:
Input:
arr = [10, 20, 5, 2, 30]
Output:
sorted array (Ascending Order): [2, 5, 10, 20, 30]
Program to sort an array in ascending order in Kotlin
package com.includehelp.basic
import java.util.*
//Main Function entry Point of Program
fun main(args: Array<String>) {
//Input Stream
val s = Scanner(System.`in`)
//Input Array Size
print("Enter number of elements in the array: ")
val size = s.nextInt()
//Create Integer array of Given size
val intArray = IntArray(size)
//Input array elements
println("Enter Arrays Elements:")
for (i in intArray.indices) {
print("intArray[$i] : ")
intArray[i] = s.nextInt()
}
//to Perform Ascending Order Sorting on integer Array
var temp:Int
for (i in intArray.indices) {
for (j in i + 1 until intArray.size) {
if (intArray[i] > intArray[j]) {
temp = intArray[i]
intArray[i] = intArray[j]
intArray[j] = temp
}
}
}
//Alternatively we can also use sort() method of Arrays
//Class in kotlin to sort in Ascending Order
//intArray.sort()
print("Ascending Order: ")
for (item in intArray) {
print("$item ")
}
}
Output
Enter number of elements in the array: 6
Enter Arrays Elements:
intArray[0] : 5
intArray[1] : 23
intArray[2] : 1
intArray[3] : 0
intArray[4] : 9
intArray[5] : 76
Ascending Order: 0 1 5 9 23 76
----------------
Enter number of elements in the array: 8
Enter Arrays Elements:
intArray[0] : 45
intArray[1] : 3
intArray[2] : 89
intArray[3] : -8
intArray[4] : -45
intArray[5] : 0
intArray[6] : 432
intArray[7] : 6
Ascending Order: -45 -8 0 3 6 45 89 432