scala 快速排序与合并排序

def sort(L: List[Int]): List[Int] = L match {
		case Nil => Nil
		case base::tail => 
		val (left, right) = tail.partition(_ < base)
		sort(left):::base::sort(right)
} 
sort(List(3, 6, 1, 0, -1)).foreach(println)



def sort(A: Array[Int]) {
	if(A.length > 1){
		val p = A.take(A.length/2)
		val q = A.takeRight(A.length - A.length/2)
		sort(p); sort(q)
		var i = 0; var j = 0
		while(i < p.length && j < q.length){
			if (p(i) < q(j)) {A(i+j) = p(i); i += 1}
			else {A(i+j) = q(j); j += 1}
		}
		while(i < p.length) {A(i+j) = p(i); i += 1}
		while(j < q.length) {A(i+j) = q(j); j += 1}
	}
}
val A = Array[Int](4, 1, 6, 7, 0, 2)
sort(A)
println(A.mkString(", "))

你可能感兴趣的:(scala 快速排序与合并排序)