From 9723ed03cf6d782bcd064947b52207ab27b48686 Mon Sep 17 00:00:00 2001 From: Alterevit Date: Thu, 22 Mar 2018 22:53:07 +0300 Subject: [PATCH] add selection sort on kotlin --- 02_selection_sort/kotlin/SeletionSortk.kt | 26 +++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 02_selection_sort/kotlin/SeletionSortk.kt diff --git a/02_selection_sort/kotlin/SeletionSortk.kt b/02_selection_sort/kotlin/SeletionSortk.kt new file mode 100644 index 0000000..d160ba0 --- /dev/null +++ b/02_selection_sort/kotlin/SeletionSortk.kt @@ -0,0 +1,26 @@ + +fun ArrayList.selectionSort(): ArrayList { + val sortedArray = arrayListOf() + for (i in 0 until size) { + val smallest = getSmallest() + sortedArray += this[smallest] + removeAt(smallest) + } + return sortedArray +} + +fun ArrayList.getSmallest(): Int { + var smallest = this[0] + var index = 0 + for (i in 1 until size) if (this[i] < smallest) { + smallest = this[i] + index = i + } + return index +} + + +fun main(args: Array) { + val array = arrayListOf(0, 2, 5, 1, 8, 23, 31, 21, 93, 213, 31, 11, 1512, 231, 341, 516, 132, 322, 421, 643) + print("sort: ${array.selectionSort()}") +}