Scala 排序算法的实现


Insert Sort

  import math.Ordering
  def iSort[T](a: List[T])(implicit ord: Ordering[T]): List[T] = {

    def insert(x: T, xs: List[T]): List[T] = xs match {
      case Nil => List(x)
      case y :: ys => if (ord.lt(x, y)) x :: xs else y :: insert(x, ys)
    }

    a match {
      case Nil => Nil
      case x :: xs =>
        insert(x, iSort(xs))
    }
  }


Quick Sort

  import math.Ordering
  def qSort[T](a: List[T])(implicit ord: Ordering[T]): List[T] = {

    if (a.length < 2) a
    else {
      val pivot = a.head
      val (first, second) = a.tail partition (x => ord.lt(x, pivot))
      qSort(first) ::: List(pivot) ::: qSort(second)
    }
  }
  
  
  //another implementation
  
  def qSort[T](a: List[T])(implicit ord: Ordering[T]): List[T] = {
    if (a.length < 2) a
    else qSort(a filter (ord.lt(a.head, _))) ++
         a.filter(ord.eq(a.head, _))) ++
         qSort(a filter (ord.gt(a.head, _)))
  }

Merge Sort

  import math.Ordering
  def mSort[T](a: List[T])(implicit ord: Ordering[T]): List[T] = {

    def merge(xs: List[T], ys: List[T]): List[T] = (xs, ys) match {

      case (Nil, ys) => ys
      case (xs, Nil) => xs
      case (a :: as, b :: bs) => if (ord.lt(a, b)) a :: merge(as, ys) 
	                                      else b :: merge(xs, bs)

    }

    val center = a.length / 2

    if (center == 0) a // when a has single element or Nil
    else {
      val (first, second) = a splitAt center

      merge(mSort(first), mSort(second))
    }

你可能感兴趣的:(Scala,AKKA)