Created
September 21, 2015 15:28
-
-
Save cnevinc/9ddd01c5dc5ceb0464b1 to your computer and use it in GitHub Desktop.
insertion sort using Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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