Advertisement
jules0707

insertion sort quadratic

Dec 18th, 2017
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.77 KB | None | 0 0
  1. // List decomposition with pattern matching
  2. // run time of isort is N*N ! not good
  3. val xs = List(7, 3, 9, 2)
  4.  
  5. // worst case x is greater than all the elements of xs so time proportional to N
  6. def insert(x: Int, xs: List[Int]): List[Int] = xs match {
  7.   case Nil => x :: Nil
  8.   case y :: ys => if(x <= y) x::xs else y::insert(x,ys)
  9. }
  10.  
  11.  
  12. // one call to insert for each element in the list so N*N quadratic!
  13. def isort(xs: List[Int]): List[Int] = xs match {
  14.   case Nil => Nil
  15.   case y :: ys => insert(y, isort(ys))
  16. }
  17.  
  18. val xsorted = isort(xs)
  19.  
  20. --------------- output -------------------
  21.  
  22. xs: List[Int] = List(7, 3, 9, 2)
  23.  
  24. insert: insert[](val x: Int,val xs: List[Int]) => List[Int]
  25.  
  26. isort: isort[](val xs: List[Int]) => List[Int]
  27.  
  28. xsorted: List[Int] = List(2, 3, 7, 9)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement