Skip to content

Instantly share code, notes, and snippets.

@cnevinc
Created September 21, 2015 15:28
Show Gist options
  • Save cnevinc/9ddd01c5dc5ceb0464b1 to your computer and use it in GitHub Desktop.
Save cnevinc/9ddd01c5dc5ceb0464b1 to your computer and use it in GitHub Desktop.
insertion sort using Kotlin
package com.example
fun insertionSort(array: IntArray) {
for ((index, value) in array.withIndex()) {
// println("the element at $index is $value")
var j = index
while (j > 0 ) {
// swap if smaller than sorted[j]
if (array[j] < array[j - 1]) {
val temp = array[j]
array[j] = array[j - 1]
array[j - 1] = temp
}
j--
}
}
}
fun main(args: Array<String>) {
val array = intArrayOf(4, 3, 5, 6, 2, 1)
array.forEach { i -> println(i) }
insertionSort(array)
array.forEach { i -> println(i) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment