I was trying to port this particular insertion sort from Haskell. I get strange incorrect output in most cases with a List longer than the input or sometimes copied values. Do you see something I am missing. Or maybe I not copying the syntax from Haskell properly:
If you provide a fix, could you use similar semantics, I was trying to understand this particular version.
object InsertionSortApp {
/*
* Based on Haskell version:
insert e [] = [e]
insert e lst@(x:xs)
| e < x = e : lst
| otherwise = x : (insert e xs)
insertionSort lst = insertionSort' lst [] where
insertionSort' [] lst = lst
insertionSort' (x:xs) lst = insertionSort' xs (insert x lst)
*/
def insert(e : Integer, lst : List[Int]) : List[Int] = {
def insertPrime(xs: List[Int]) : List[Int] = xs match {
case Nil => List(e)
case x :: xs if (e < x) => e :: lst
case x :: xs => x :: insertPrime(xs)
}
return insertPrime(lst)
}
def insertionSort(origList: List[Int]) : List[Int] = {
def insertionSortPrime(xs: List[Int], lst: List[Int]) : List[Int] = xs match {
case Nil => lst
case x :: xs => insertionSortPrime(xs, insert(x, lst))
}
insertionSortPrime(origList, List())
}
def main(args : Array[String]) : Unit = {
println("Running - Insertion Sort Test")
val lst = List(1, 7, 3, 4, 5)
println("Test: " + (insertionSort(lst)))
}
} // End of object //
In
insertPrime, change this lineto