Created
July 18, 2014 06:06
-
-
Save peel/9edd0a8906ae884c0d47 to your computer and use it in GitHub Desktop.
mergesort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Mergesort { | |
def sort(items: List[Int], sorter: (Int, Int) => Boolean): List[Int] = { | |
if (items.length == 0) { | |
List[Int](); | |
} else if (items.length == 1) { | |
items; | |
} else { | |
merge( | |
sort(items.slice(0, items.length / 2), sorter), | |
sort(items.slice(items.length / 2, items.length), sorter), | |
List[Int](), | |
sorter); | |
} | |
} | |
def merge( | |
items1: List[Int], | |
items2: List[Int], sorted: List[Int], | |
ascending: (Int, Int) => Boolean): List[Int] = { | |
(items1, items2) match { | |
case (List(), List()) => sorted | |
case (List(), _) => | |
merge(items1, items2.drop(1), sorted ::: List(items2.head), ascending) | |
case (_, List()) => | |
merge(items1.drop(1), items2, sorted ::: List(items1.head), ascending) | |
case _ => { | |
if (ascending(items1.head, items2.head)) { | |
merge(items1.drop(1), items2, sorted ::: (List(items1.head)), ascending); | |
} else { | |
merge(items1, items2.drop(1), sorted ::: (List(items2.head)), ascending); | |
} | |
} | |
} | |
} | |
def main(args: Array[String]): Unit = { | |
// Example | |
val sorted = sort(List[Int](4, 2, 35, 1, 8, 79, 60), (a, b) => a <= b); | |
println(sorted.mkString(",")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment