• Scala实现冒泡排序、归并排序和快速排序


    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))
      }

    未完成,待整理

  • 相关阅读:
    eclipse快捷键
    Struts2框架(8)---Struts2的输入校验
    Struts2框架(5)---result结果集
    Spring框架(6)---AspectJ实现AOP
    Spring框架(4)---AOP讲解铺垫
    Spring框架(3)---IOC装配Bean(注解方式)
    Spring框架(2)---IOC装配Bean(xml配置方式)
    Spring框架(1)---Spring入门
    Mybatis框架(5)---动态sql
    Mybatis框架(4)---输入输出映射
  • 原文地址:https://www.cnblogs.com/jchubby/p/5449380.html
Copyright © 2020-2023  润新知