zoukankan      html  css  js  c++  java
  • Scala冒泡排序、快排、归并

    感谢heybiiiiii同学

    http://blog.csdn.net/qq1010885678/article/details/46755749

    1、冒泡排序

    def sort(list: List[Int]): List[Int] = list match {
        case List() => List()
        case head :: tail => compute(head, sort(tail))
      }
    
      def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
        case List() => List(data)
        case head :: tail => if (data <= head) data :: dataSet else head :: compute(data, tail)
      }
    
    def main(args: Array[String]) {
        val list = List(3, 12, 43, 23, 7, 1, 2, 0)
        println(sort(list))
      }

    2、归并排序

    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))
        }
      }
    
    def main(args: Array[String]) {
        val list = List(3, 12, 43, 23, 7, 1, 2, 0)
        println(mergedSort((x: Int, y: Int) => x < y)(list))
      }

    3、快速排序

      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)
        }
      }
    
    def main(args: Array[String]) {
        val list = List(3, 12, 43, 23, 7, 1, 2, 0)
        println(quickSort(list))
      }
  • 相关阅读:
    P3952 [NOIP2017 提高组] 时间复杂度
    1905. 统计子岛屿
    1102 Invert a Binary Tree (25 分)
    P1077 [NOIP2012 普及组] 摆花
    P3915 树的分解
    P1045 [NOIP2003 普及组] 麦森数
    P4961 小埋与扫雷
    P1123 取数游戏
    P1460 [USACO2.1]健康的荷斯坦奶牛 Healthy Holsteins
    CF1059B Forgery
  • 原文地址:https://www.cnblogs.com/alexRose/p/8029294.html
Copyright © 2011-2022 走看看