// // functions to use insertion sort to sort list of integers, // array of integers // // lists are immutable so we return the sorted result def insertL(l : List[Int], elem : Int) : List[Int] = { if (l.isEmpty) { List(elem) } else if (elem < l.head) { elem :: l } else { l.head :: insertL(l.tail, elem) } } def insertionSortL(l : List[Int]) : List[Int] = { var out = List[Int]() for (elem <- l) { out = insertL(out, elem) } out } // arrays are mutable so we can sort in place def insertA(a : Array[Int], indexToInsert : Int) { // insert element a(indexToInsert) into part of array to the left // doing repeated exchanges here is simple but maybe not efficient var index = indexToInsert while ((index > 0) && (a(index-1) > a(index))) { val temp = a(index-1) a(index-1) = a(index) a(index) = temp index -= 1 } } def insertionSortA(a : Array[Int]) { for (i <- 1 until a.length) { insertA(a, i) } }