Skip to content

Commit afe7bd6

Browse files
committed
Merge Sort
1 parent d8f8874 commit afe7bd6

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

6.Sorting/MergeSort.scala

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
def mergeSort(xs :List[Int]): List[Int] = {
2+
val n = xs.length
3+
if(n <= 1) xs
4+
else{
5+
val (first, second) = xs.splitAt(n/2)
6+
def merge(xs:List[Int], ys:List[Int]): List[Int] = (xs, ys) match {
7+
case (Nil, ys) => ys
8+
case (xs, Nil) => xs
9+
case (x::xs, y::ys) =>
10+
if (x <= y) x :: merge(xs,y :: ys)
11+
else y :: merge(x::xs, ys)
12+
}
13+
merge(mergeSort(first),mergeSort(second))
14+
}
15+
}
16+
println(mergeSort(6::5::4::3::2::1::Nil))

0 commit comments

Comments
 (0)