Created
April 2, 2011 07:08
-
-
Save songpp/899301 to your computer and use it in GitHub Desktop.
scala示例
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
package t1 | |
object Just { | |
def main(arg : Array[String]) : Unit = { | |
val a = new Array[Int](10) | |
val x = Array(6, 23, 123, 5563, 345, 11); | |
quicksort(x) foreach println | |
mergesort(_>_)(x.toList) foreach println | |
} | |
def quicksort(args : Array[Int]) : Array[Int] = { | |
if (args.size <= 1) | |
args | |
else { | |
val m = args(args.length >>> 1) | |
Array.concat( | |
quicksort(args.filter(m >)), | |
quicksort(args.filter(m ==)), | |
quicksort(args.filter(m <))) | |
} | |
} | |
def mergesort(compare : (Int, Int) => Boolean)(col : List[Int]) : List[Int] = { | |
def merge(col1 : List[Int], col2 : List[Int]) : List[Int] = { | |
if(col1.isEmpty) col2 | |
else if(col2.isEmpty) col1 | |
else if(compare(col1.head,col2.head)) col1.head :: merge(col1.tail,col2) | |
else col2.head :: merge(col1,col2.tail) | |
} | |
val n = col.length >>> 1 | |
if(n == 0) col | |
else merge(mergesort(compare)(col.take(n)),mergesort(compare)(col.drop(n))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment