forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSorts.scala
68 lines (63 loc) · 1.41 KB
/
Sorts.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import scala.util.control.Breaks._
/**
* 冒泡排序、插入排序、选择排序
*
* Author: yangchuz
*/
object Sorts {
def main(args: Array[String]): Unit ={
// 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], n:Int): Array[Int] = {
val n = arr.length
breakable {
for(i <- (n-1) to (1, -1)){
var flag = false
for(j <- 0 until i){
if(arr(j) > arr(j+1)){
val tmp = arr(j)
arr(j) = arr(j+1)
arr(j+1) = tmp
flag = true
}
}
if(!flag){
break
}
}
}
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
}
}