Skip to content

Commit 686daf0

Browse files
committed
Merge Sort
1 parent afe7bd6 commit 686daf0

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

6.Sorting/MergeSort.scala

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
def mergeSort(xs :List[Int]): List[Int] = {
1+
def mergeSort[T](xs :List[T])(lt: (T, T) => Boolean): List[T] = {
22
val n = xs.length
33
if(n <= 1) xs
44
else{
55
val (first, second) = xs.splitAt(n/2)
6-
def merge(xs:List[Int], ys:List[Int]): List[Int] = (xs, ys) match {
6+
def merge(xs:List[T], ys:List[T]): List[T] = (xs, ys) match {
77
case (Nil, ys) => ys
88
case (xs, Nil) => xs
99
case (x::xs, y::ys) =>
10-
if (x <= y) x :: merge(xs,y :: ys)
10+
if (lt(x, y)) x :: merge(xs,y :: ys)
1111
else y :: merge(x::xs, ys)
1212
}
13-
merge(mergeSort(first),mergeSort(second))
13+
merge(mergeSort(first)(lt),mergeSort(second)(lt))
1414
}
1515
}
16-
println(mergeSort(6::5::4::3::2::1::Nil))
16+
println(mergeSort(6::5::4::3::2::1::Nil)((a:Int, b:Int)=> a<=b))

0 commit comments

Comments
 (0)