Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Insertion Sort Algorithm Program in Kotlin

In this article, we will write an insertion Sort Algorithm Program in Kotlin. Below is the complexity comparison of insertion sort.

Best-case performance: O(n) comparisons, O(1) swaps
Average performance: О(n2) comparisons, swaps
Worst-case space complexity: О(n) total, O(1) auxiliary

Source Code:
fun main(arg: Array)
{
    try
    {
        print("Enter size of array : ")
        var n = readLine()!!.toInt()

        println("Enter elements : ")
        var A = Array(n, { 0 })
        for (i in 0 until n) {
            A[i] = readLine()!!.toInt()
        }

        insertion_sort(A,A.size)

        println("Sorted array is : ")
        for (i in 0 until n){
            print("${A[i]}  ")
        }
    }
    catch(e: Exception)
    {
        print("$e")
    }
}

/* Function to sort an array using insertion sort*/
fun insertion_sort(A: Array, n : Int)
{
    var n = A.size
    var i: Int
    for (j in 1 until n)
    {
        var key = A[j]
        i = j - 1
        while (i >= 0 && A[i] > key) {
            A[i + 1] = A[i]
            i--
        }
        A[i + 1] = key
    }
}
Output:
Enter size of array : 5
Enter elements :
12
10
14
18
16
Sorted array is :
10  12  14  16  18
Insertion Sort Algorithm Program in Kotlin - Output

Description:
In this program, we will take the size of an array from the end user. Next, it will ask to enter the number of elements of array. It will be stored in array A[i] = readLine()!!.toInt() using for loop. At this point elements of an array are not in sorted sequence.

Next, we have called the function fun insertion_sort(A: Array, n : Int), which accepts an array to be sorted and size of an array. A sorted array will be printed using print() function. More in this, we have used try{} catch{} blocks to validate user input.


This post first appeared on Ask For Program, please read the originial post: here

Share the post

Insertion Sort Algorithm Program in Kotlin

×

Subscribe to Ask For Program

Get updates delivered right to your inbox!

Thank you for your subscription

×