码迷,mamicode.com
首页 > 编程语言 > 详细

scala冒泡排序

时间:2016-06-01 06:47:27      阅读:706      评论:0      收藏:0      [点我收藏+]

标签:

 

 

scala冒泡排序:

object Maopao {
  def main(args: Array[String]) {
    val list = List(1, 23, 432, 10, 23, 42, 3, 23, 8, 23, 4)
    print(sort2(list))
    println()
    val arr = Array(2, 5, 6, 7, 8, 10, 34, 656, 3)
    sort(arr)
    printArr(arr)
  }
 //基本的冒泡排序,类似java写法
  def sort(arr: Array[Int]) = {
    for (i <- 0 until arr.length; j <- 0 until arr.length - 1; if (arr(j) > arr(j + 1))) {
      val temp = arr(j)
      arr(j) = arr(j + 1)
      arr(j + 1) = temp
    }
  }

  def printArr(arr: Array[Int]) = {
    for (i <- 0 until arr.length)
      print(arr(i) + ",")
  }

  def sort2(list: List[Int]): List[Int] = list match {
    case List() => List()
    case head :: tail => comput(head, sort2(tail))
  }

  def comput(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
    case List() => List(data)
    case head :: tail => if (data <= head) data :: dataSet else head :: comput(data, tail)
  }
}

  

scala冒泡排序

标签:

原文地址:http://www.cnblogs.com/wujinsen/p/5548289.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!