Created
July 21, 2014 01:11
-
-
Save mofas/04ddb9734c4d783417f5 to your computer and use it in GitHub Desktop.
scala sort
This file contains hidden or 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 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) } | |
} | |
} |
This file contains hidden or 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 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))) | |
} | |
} | |
} |
This file contains hidden or 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 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