Selection Sort
Algorithms #algorithms #sortingFind minimum element on each iteration and place it in the right place.
- Time complexity is O(n2) because in any case all comparisons will be made
fun main() {
val arr = intArrayOf(2, 1, 10, 0, 2)
println(arr.contentToString())
selectionSort(arr)
println("sorted: ${arr.contentToString()}")
}
fun selectionSort(arr: IntArray) {
val n = arr.size
for (i in 0 until n.dec()) {
var min = i
for (j in i until n) {
if (arr[j] < arr[min]) {
min = j
}
}
// swap
val tmp = arr[i]
arr[i] = arr[min]
arr[min] = tmp
}
}