-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBubbleSortImproved.kt
44 lines (40 loc) · 986 Bytes
/
BubbleSortImproved.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
package sorting
/**
* improved bubble sort
*
* worst time: n²
* the best time: n
* average time: n²
*
* amount of memory: 1
*/
fun <T : Comparable<T>> Array<T>.bubbleSortImproved() {
val array = this
var isSorted = true
for (i in 0 until size - 1) {
for (j in 0 until size - 1 - i) {
if (array[j] > array[j + 1]) {
isSorted = false
array[j] = array[j + 1].apply {
array[j + 1] = array[j]
}
}
}
if (isSorted) break
}
}
fun <T : Comparable<T>> MutableList<T>.bubbleSortImproved() {
val list = this
var isSorted = true
for (i in 0 until size - 1) {
for (j in 0 until size - 1 - i) {
if (list[j] > list[j + 1]) {
isSorted = false
list[j] = list[j + 1].apply {
list[j + 1] = list[j]
}
}
}
if (isSorted) break
}
}