Skip to content

Commit f06edbd

Browse files
authored
Add Selection Sort in Kotlin (#5002)
Implemented selection sort
1 parent fed8b68 commit f06edbd

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

archive/k/kotlin/SelectionSort.kt

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import kotlin.system.exitProcess
2+
3+
fun main(args: Array<String>) {
4+
val nums: IntArray = errorChecking(args)
5+
selectionSort(nums)
6+
outputList(nums)
7+
}
8+
9+
fun usageError() {
10+
println("Usage: please provide a list of at least two integers to sort in the format \"1, 2, 3, 4, 5\"")
11+
}
12+
13+
fun errorChecking(args: Array<String>): IntArray {
14+
val nums: IntArray
15+
try {
16+
nums = args[0].split(", ").map { it.toInt() }.toIntArray()
17+
} catch (e: Exception) {
18+
usageError()
19+
exitProcess(1)
20+
}
21+
if (nums.size < 2) {
22+
usageError()
23+
exitProcess(1)
24+
}
25+
return nums
26+
}
27+
28+
fun selectionSort(nums: IntArray) {
29+
for (i in 0 until nums.count() - 1) {
30+
31+
var smallestIndex: Int = i
32+
for (j in i + 1 until nums.count()) {
33+
if (nums[j] < nums[smallestIndex]) {
34+
smallestIndex = j
35+
}
36+
}
37+
38+
var swap: Int = nums[i]
39+
nums[i] = nums[smallestIndex]
40+
nums[smallestIndex] = swap
41+
}
42+
}
43+
44+
fun outputList(nums: IntArray) {
45+
for (i in nums.indices) {
46+
if (i == nums.count() - 1) {
47+
println("${nums[i]}")
48+
return
49+
}
50+
print("${nums[i]}, ")
51+
}
52+
}

0 commit comments

Comments
 (0)