越来越喜欢Scala了,语法超简洁,3个排序算法30行左右搞定,还支持泛型,升序或者降序,强大的语言。
import scala.util.Random
/**
* Created by fhqplzj on 16-7-7 at 下午9:04.
*/
object SortInScala {
/**
* 插入排序
* @param xs
* @param ord
* @tparam T
* @return
*/
def isort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = {
def insert(x: T, xs: List[T]): List[T] = xs match {
case List() => List(x)
case y :: ys => if (ord.lt(x, y)) x :: xs else y :: insert(x, ys)
}
xs match {
case List() => xs
case x :: xs1 => insert(x, isort(xs1))
}
}
/**
* 归并排序
* @param xs
* @param ord
* @tparam T
* @return
*/
def msort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = {
def merge(xs: List[T], ys: List[T]): List[T] = (xs, ys) match {
case (Nil, _) => ys
case (_, Nil) => xs
case (x :: xs1, y :: ys1) => if (ord.lt(x, y)) x :: merge(xs1, ys) else y :: merge(xs, ys1)
}
val n: Int = xs.length / 2
if (n == 0) xs
else {
val (left, right): (List[T], List[T]) = xs.splitAt(n)
merge(msort(left)(ord), msort(right)(ord))
}
}
/**
* 快速排序
* @param xs
* @param ord
* @tparam T
* @return
*/
def qsort[T](xs: List[T])(implicit ord: Ordering[T]): List[T] = xs match {
case List() => xs
case x :: xs1 => {
val (left, right): (List[T], List[T]) = xs1.partition(ord.lt(_, x))
qsort(left)(ord) ::: List(x) ::: qsort(right)(ord)
}
}
def main(args: Array[String]) {
val random: Random = new Random(System.nanoTime())
// 原始数据
val data: List[Int] = List.tabulate(10)(i => random.nextInt(100))
println("data = " + data)
// 升序
val ascend: List[Int] = qsort(data)
println("ascend = " + ascend)
// 降序
val descend: List[Int] = qsort(data)(Ordering.Int.reverse)
println("descend = " + descend)
}
}