-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSelectionSort.kt
45 lines (42 loc) · 923 Bytes
/
SelectionSort.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
package sorting
/**
* selection sort algorithm
*
* worst time: n²
* the best time: n²
* average time: n²
*
* amount of memory: 1
*/
fun <T : Comparable<T>> Array<T>.selectionSort() {
val array = this
for (i in 0 until size - 1) {
var min = i
for (j in i + 1 until size) {
if (array[min] > array[j]) {
min = j
}
}
if (min != i) {
array[min] = array[i].apply {
array[i] = array[min]
}
}
}
}
fun <T : Comparable<T>> MutableList<T>.selectionSort() {
val list = this
for (i in 0 until size - 1) {
var min = i
for (j in i + 1 until size) {
if (list[min] > list[j]) {
min = j
}
}
if (min != i) {
list[min] = list[i].apply {
list[i] = list[min]
}
}
}
}