-
Notifications
You must be signed in to change notification settings - Fork 108
/
CocktailShakerSort.kt
50 lines (41 loc) · 1.07 KB
/
CocktailShakerSort.kt
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
fun main(args : Array<String>) {
val sorted = cocktailShakerSort(intArrayOf(4, 4, -4, 751, 7, 9, 5, 37564, -54, 1, 0, 100))
sorted.forEach {
print("$it, ")
}
}
fun cocktailShakerSort(input:IntArray):IntArray{
if(input.size <= 1){
return input
}
var start = 0
var end = input.size -2
var unsorted = true
while(unsorted) {
unsorted = false
for (i in start..end) {
if (input[i] > input[i + 1]) {
val temp = input[i + 1]
input[i + 1] = input[i]
input[i] = temp
unsorted = true
}
}
if (!unsorted) {
break
} else {
unsorted = false
end--
for (i in end downTo start) {
if (input[i] > input[i + 1]) {
val temp = input[i + 1]
input[i + 1] = input[i]
input[i] = temp
unsorted = true
}
}
start++
}
}
return input
}