Skip to content

Commit 2f357a0

Browse files
jrg94pascalecu
authored andcommitted
Added Insertion Sort in Kotlin (TheRenegadeCoder#4999)
Implemented insertion sort
1 parent 77cceae commit 2f357a0

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

archive/k/kotlin/InsertionSort.kt

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import kotlin.system.exitProcess
2+
3+
fun main(args: Array<String>) {
4+
val nums: IntArray = errorChecking(args)
5+
insertionSort(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 insertionSort(nums: IntArray) {
29+
for (i in 1 until nums.count()) {
30+
val toMove: Int = nums[i]
31+
var j: Int = i - 1
32+
33+
while (j >= 0 && nums[j] > toMove) {
34+
nums[j + 1] = nums[j]
35+
j = j - 1
36+
}
37+
38+
nums[j + 1] = toMove
39+
}
40+
}
41+
42+
fun outputList(nums: IntArray) {
43+
for (i in nums.indices) {
44+
if (i == nums.count() - 1) {
45+
println("${nums[i]}")
46+
return
47+
}
48+
print("${nums[i]}, ")
49+
}
50+
}

0 commit comments

Comments
 (0)