-
Notifications
You must be signed in to change notification settings - Fork 0
/
BubbleSort.kt
37 lines (34 loc) · 792 Bytes
/
BubbleSort.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
package sorting
/**
* bubble sort
*
* worst time: n²
* the best time: n²
* average time: n²
*
* amount of memory: 1
*/
fun <T : Comparable<T>> Array<T>.bubbleSort() {
val array = this
for (i in 0 until size - 1) {
for (j in 0 until size - 1 - i) {
if (array[j] > array[j + 1]) {
array[j] = array[j + 1].apply {
array[j + 1] = array[j]
}
}
}
}
}
fun <T : Comparable<T>> MutableList<T>.bubbleSort() {
val list = this
for (i in 0 until size - 1) {
for (j in 0 until size - 1 - i) {
if (list[j] > list[j + 1]) {
list[j] = list[j + 1].apply {
list[j + 1] = list[j]
}
}
}
}
}