-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathSelectionSort.kt
More file actions
32 lines (27 loc) · 862 Bytes
/
SelectionSort.kt
File metadata and controls
32 lines (27 loc) · 862 Bytes
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
package algorithmdesignmanualbook.sorting
import java.util.*
fun main() {
val elements = "SELECTIONSORT".split("").filter(String::isNotBlank)
val input = elements.toTypedArray()
selectionSort(input)
println(Arrays.toString(input))
}
/**
* Identify the smallest element from unsorted portion and put it at the end of the sorted portion
*/
private fun selectionSort(array: Array<String>) {
for (i in 0..array.lastIndex) {
var smallestElementIndex = i
for (j in (i + 1)..array.lastIndex) {
if (array[smallestElementIndex] > array[j]) {
smallestElementIndex = j
}
}
swap(array, i, smallestElementIndex)
}
}
private fun swap(array: Array<String>, index1: Int, index2: Int) {
val temp = array[index1]
array[index1] = array[index2]
array[index2] = temp
}