Home » Kotlin

Program for insertion sort in Kotlin

In this article, we are going to learn how to implement an insertion sort in Kotlin? Here, you will find what is insertion sort, its algorithm, program with the explanation?
Submitted by Aman Gautam, on December 13, 2017

Insertion sort is a sorting algorithm in which we maintain a sorted array in the beginning of the list and an unsorted list simultaneously. We choose an element from an unsorted array and place it in the sorted sequence of elements at its correct position. We repeat the same step till the whole array get sorted.

Algorithm

    INSERTION-SORT(A)
    1.	for j = 1 to A.length
    2.	    key = A[j]
    3.	i = j-1
    4.	while i> 0 and A[i] > key
    5.	         A[i+1]=A[i]
    6.	         I = i-1
    7.	     A[i+1] = key

Algorithm source from Introduction to Algorithms 3rd Edition by cormen.

This algorithm takes O(n2) time in worst case. However, in the best case, it does only one comparison in each phase. The best case is if the array is already sorted. This is best for a situation where an array is nearly sorted or size of the problem is small.

Program

fun insertion_sort(A: Array<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
    }
}

fun main(arg: Array<String>) {
    print("Enter no. of elements :")
    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)

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

Output

Enter no. of elements :5
Enter elements :
22
12
33
32
11
Sorted array is :
11  12  22  32  33





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.