Skip to content

Instantly share code, notes, and snippets.

@mofas
Created July 21, 2014 01:11
Show Gist options
  • Save mofas/04ddb9734c4d783417f5 to your computer and use it in GitHub Desktop.
Save mofas/04ddb9734c4d783417f5 to your computer and use it in GitHub Desktop.
scala sort
object InsertionSort{
def sort(xs : List[Int]): List[Int] = {
def insert(sorted : List[Int], e : Int)= {
sorted.takeWhile( x => (x < e)) ++ List(e) ++ sorted.dropWhile( x => (x < e))
}
xs.foldLeft(List[Int]()) { (sorted, e) => insert(sorted, e) }
}
}
object MergeSort{
def getMid(length: Int) : Int = {
length/2
}
def merge(a : List[Int], b: List[Int]): List[Int] = {
if(a.isEmpty) b
else if(b.isEmpty) a
else if(a.head < b.head) a.head +: merge(a.tail, b)
else b.head +: merge(a, b.tail)
}
def sort(xs : List[Int]): List[Int] = {
if(xs.length == 1) xs
else{
val mid = getMid(xs.length)
merge(sort(xs.take(mid)), sort(xs.drop(mid)))
}
}
}
object mergeSortOptimized {
def getMid(length: Int) : Int = {
length/2
}
def merge(a : List[Int], b: List[Int]): List[Int] = {
if(a.isEmpty) b
else if(b.isEmpty) a
else if(a.last < b.head) a++b
else if(a.head < b.head) a.head +: merge(a.tail, b)
else b.head +: merge(a, b.tail)
}
def sort(xs : List[Int]): List[Int] = {
if(xs.length < 7) InsertionSort.sort(xs)
else{
val mid = getMid(xs.length)
merge(sort(xs.take(mid)), sort(xs.drop(mid)))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment