@羲凡——只为了更好的活着
Scala 实现归并排序、快速排序
原文链接 https://blog.csdn.net/qq1010885678/article/details/46755749 。这位仁兄对scala的list、模式匹配和递归的理解非常深刻,第一看惊为天作,这个算法还能这么写,牛逼呀。
1.归并排序
def mergedSort[T](less: (T, T) => Boolean)(list: List[T]): List[T] = {
def merged(xList: List[T], yList: List[T]): List[T] = {
(xList, yList) match {
case (Nil, _) => yList
case (_, Nil) => xList
case (x :: xTail, y :: yTail) => {
if (less(x, y))
x :: merged(xTail, yList)
else
y :: merged(xList, yTail)
}
}
}
val n = list.length / 2
if (n == 0) list
else {
val (x, y) = list splitAt n
merged(mergedSort(less)(x), mergedSort(less)(y))
}
}
2.快速排序
def quickSort(list:List[Int]): List[Int] ={
list match {
case Nil => Nil
case List() => List()
case head :: tail =>
val (left,right) = tail.partition(_ < head)
quickSort(left) ::: head :: quickSort(right)
}
}
====================================================================
@羲凡——只为了更好的活着
若对博客中有任何问题,欢迎留言交流