Advertisement
Guest User

Untitled

a guest
Nov 14th, 2014
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.80 KB | None | 0 0
  1. import scala.annotation.tailrec
  2.  
  3. /**
  4.  * User: Andrei Gerasimov
  5.  * Date: 14.11.2014
  6.  */
  7. object MergeSort {
  8.  
  9.   val data: List[Int] = List(5, 4, 3, 7, 9, 3, 2, 3, 1, 0, -1, 5, 6)
  10.  
  11.   def main(args: Array[String]): Unit = {
  12.     println(sort(data))
  13.   }
  14.  
  15.   private def sort(list: List[Int]): List[Int] = {
  16.  
  17.     @tailrec
  18.     def merge(left: List[Int], right: List[Int], acc: List[Int]): List[Int] = (left, right) match {
  19.       case (Nil, _) => acc.reverse ::: right
  20.       case (_, Nil) => acc.reverse ::: left
  21.       case (x :: xs, y :: ys) =>
  22.         if (x < y) merge(xs, right, x :: acc)
  23.         else merge(left, ys, y :: acc)
  24.     }
  25.  
  26.     val n = list.length / 2
  27.     if (n == 0) list
  28.     else {
  29.       val (left, right) = list splitAt n
  30.       merge(sort(left), sort(right), Nil)
  31.     }
  32.   }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement