Insertion sort improves upon both Bubble sort and Selection sort as it uses copy instead of swap and latter being more expensive operation as compared to former. We start from the leftmost element of an array and while in the process of iteration left part of the array from current element is always sorted. In each iteration we find the right place for current element among all of its left elements. The worst case running time of this algorithm still remains same because finding right position for an element will take O(n) so actual running time will be (1 + 2 + ... + n -1 + n) = O(n^2)
10,9,11,5,2 valueToSwap -> 10
9,10,11,5,2 valueToSwap -> 9
9,10,11,5,2 valueToSwap -> 11
5,9,10,11,2 valueToSwap -> 5
2,5,9,10,11 valueToSwap -> 2
Sorted Array -> 2,5,9,10,11
package com.thescalatutorial.examples object InsertionSort { def insertionSort(array: Array[Int]) = { def insertionSortRecursive(array: Array[Int], start: Int): Array[Int] = { start match { case _ if (start > array.size - 1) => array case _ => var j = start; val valueToSwap = array(start) while(j > 0 && array(j - 1) > valueToSwap) { array(j) = array(j - 1) j -= 1 } array(j) = valueToSwap println(array.mkString(",") + " valueToSwap -> " + valueToSwap) insertionSortRecursive(array, start + 1) } } insertionSortRecursive(array, 0) } def main(args: Array[String]) { val sortedArray = insertionSort(Array(10,9,11,5,2)) println("Sorted Array -> " + sortedArray.mkString(",")) } }Running above program will produce following output:
10,9,11,5,2 valueToSwap -> 10
9,10,11,5,2 valueToSwap -> 9
9,10,11,5,2 valueToSwap -> 11
5,9,10,11,2 valueToSwap -> 5
2,5,9,10,11 valueToSwap -> 2
Sorted Array -> 2,5,9,10,11