Scala编程之插入排序

一、总述

       排序,这是一个十分经典且实用的算法。不论,你学习的何种编程语言,排序算法都是作为软件工程师或研发工程师所必须掌握的东西。最近一直在学习Scala,下面就通过Scala语言实现插入排序算法。

二、插入排序算法

       定义一个名为InsertSort的object对象

/**
  * Created by user on 2016/1/22.
  */
object InsertSort {
   def sort(x: List[Int]): List[Int] = {
       if(x.isEmpty){
          Nil
       }else{
          insert(x.head,sort(x.tail))
       }
   }

   def insert(x: Int,xs: List[Int]): List[Int] = {
       if(xs.isEmpty || x <= xs.head){
          x :: xs
       }else{
          xs.head :: insert(x,xs.tail)
       }
   }

   def main(args: Array[String]) {
       val num = 2 :: 1 :: 4 :: 3 :: 5 :: 7 :: 0 :: Nil
       val result = sort(num)
       println("Insert Sort: " + result)
   }
}

三、测试结果

       Insert Sort: List(0, 1, 2, 3, 4, 5, 7)

猜你喜欢

转载自zh-workhard-java.iteye.com/blog/2273318