# 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(n^{2}) 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

TOP Interview Coding Problems/Challenges

- Run-length encoding (find/print frequency of letters in a string)
- Sort an array of 0's, 1's and 2's in linear time complexity
- Checking Anagrams (check whether two string is anagrams or not)
- Relative sorting algorithm
- Finding subarray with given sum
- Find the level in a binary tree with given sum K
- Check whether a Binary Tree is BST (Binary Search Tree) or not
- 1[0]1 Pattern Count
- Capitalize first and last letter of each word in a line
- Print vertical sum of a binary tree
- Print Boundary Sum of a Binary Tree
- Reverse a single linked list
- Greedy Strategy to solve major algorithm problems
- Job sequencing problem
- Root to leaf Path Sum
- Exit Point in a Matrix
- Find length of loop in a linked list
- Toppers of Class
- Print All Nodes that don't have Sibling
- Transform to Sum Tree
- Shortest Source to Destination Path

Comments and Discussions

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