Skip to content

Instantly share code, notes, and snippets.

@samidarko
Created August 30, 2016 15:27
Show Gist options
  • Save samidarko/5b42c6df9c364b4f28728c24fbac8ccf to your computer and use it in GitHub Desktop.
Save samidarko/5b42c6df9c364b4f28728c24fbac8ccf to your computer and use it in GitHub Desktop.
Insertion sort imperative and functional
/**
* Created by vincentdupont on 26/8/16.
*/
import util.Random
object InsertionSort extends App {
def sortImp(a: Array[Int]) : Array[Int] = {
var key, i : Int = 0
for (j <- 1 until a.length) {
key = a(j)
i = j-1
while (i >= 0 && a(i) > key) {
a(i+1) = a(i)
i -= 1
}
a(i+1) = key
}
a
}
var randomArray = Seq.fill(6)(Random.nextInt(100)).toArray
assert(sortImp(randomArray) sameElements randomArray.sorted)
def sortFun(a: List[Int]) : List[Int] = {
def insert(b: List[Int]) : List[Int] = b match {
case Nil => List(a.head)
case y::ys => if (a.head < y) a.head :: y :: ys else y :: insert(ys)
}
a match {
case Nil => Nil
case x::Nil => List(x)
case x::xs => insert(sortFun(xs))
}
}
assert(sortFun(List()) == Nil)
assert(sortFun(List(5)) == List(5))
val randomList = Seq.fill(6)(Random.nextInt(100)).toList
assert(sortFun(randomList) equals randomList.sorted)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment