From 66c64c532c4cef162e9800dd8ec8f5d66297db57 Mon Sep 17 00:00:00 2001 From: yangchuz Date: Tue, 23 Oct 2018 17:52:09 +0800 Subject: [PATCH] Scala implementation for bubble sort, insertion sort and selection sort. --- scala/11_sorts/Sorts.scala | 49 ++++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 4 deletions(-) diff --git a/scala/11_sorts/Sorts.scala b/scala/11_sorts/Sorts.scala index 81124ef..dfce2d7 100644 --- a/scala/11_sorts/Sorts.scala +++ b/scala/11_sorts/Sorts.scala @@ -1,13 +1,21 @@ import scala.util.control.Breaks._ + +/** + * 冒泡排序、插入排序、选择排序 + * + * Author: yangchuz + */ object Sorts { def main(args: Array[String]): Unit ={ - println(bubbleSort(Array(0, 3, 7, 6, 4, 5, 1, 2)).mkString(", ")) +// println(bubbleSort(Array(0, 6, 2, 3, 8, 5, 6, 7), 8).mkString(", ")) +// println(insertSort(Array(0, 6, 2, 3, 8, 5, 6, 7), 8).mkString(", ")) + println(selectionSort(Array(0, 6, 2, 3, 8, 5, 6, 7), 8).mkString(", ")) } - def bubbleSort(arr: Array[Int]): Array[Int] = { - val l = arr.length + def bubbleSort(arr: Array[Int], n:Int): Array[Int] = { + val n = arr.length breakable { - for(i <- (l-1) to (1, -1)){ + for(i <- (n-1) to (1, -1)){ var flag = false for(j <- 0 until i){ if(arr(j) > arr(j+1)){ @@ -24,4 +32,37 @@ object Sorts { } arr } + + def insertSort(arr: Array[Int], n:Int): Array[Int] = { + for(i <- 1 until n){ + val tmp = arr(i) + breakable{ + for(j <- (i-1) to (0, -1)){ + if(tmp < arr(j)){ + arr(j+1) = arr(j) + }else{ + arr(j+1) = tmp + break + } + } + } + } + arr + } + + def selectionSort(arr: Array[Int], n:Int): Array[Int] = { + for(i <- 0 until n){ + var min = i + for(j <- (i + 1) until n){ + if(arr(j) < arr(min)){ + min = j + } + } + + val tmp = arr(i) + arr(i) = arr(min) + arr(min) = tmp + } + arr + } }