34.對List進行高效的排序和倒排序代碼實戰


package ce.scala.pp

object MergedSort {
  def main(args: Array[String]): Unit = {
    
    def mergedsort[T] (less : (T,T) => Boolean) (input : List[T]) : List[T] ={   //less指定元素排序的算法  input是指具體排序的對象
      def merge(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 :: merge(xtail, yList)
        else y :: merge(xList, ytail)
      }
      
      val n = input.length / 2
      if(n == 0) input 
      else {
        val (x, y) = input splitAt n  //把要排序的列表input平均分成兩個列表
        merge(mergedsort(less)(x), mergedsort(less)(y))  //先對分後的兩個列表歸併排序,再對排好的有序表進行歸併
      }
    }
    
    println(mergedsort( ( x : Int ,y : Int) => x < y) (List(2,8,1)))
    val reversed_mergedsort = mergedsort((x : Int, y : Int) => x < y) _   //偏函數   下劃線代表第二個參數沒有傳入
    println(reversed_mergedsort(List(9,3,5,1)))
  }
  
 
}
輸出:

List(1, 2, 8)
List(1, 3, 5, 9)


參考資料來源於大數據夢工廠 深入淺出scala 第34講 由王家林老師講解


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章