Skip to content

Commit 9723ed0

Browse files
alterevitegonSchiele
authored andcommitted
add selection sort on kotlin
1 parent 2ff9912 commit 9723ed0

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
2+
fun ArrayList<Int>.selectionSort(): ArrayList<Int> {
3+
val sortedArray = arrayListOf<Int>()
4+
for (i in 0 until size) {
5+
val smallest = getSmallest()
6+
sortedArray += this[smallest]
7+
removeAt(smallest)
8+
}
9+
return sortedArray
10+
}
11+
12+
fun ArrayList<Int>.getSmallest(): Int {
13+
var smallest = this[0]
14+
var index = 0
15+
for (i in 1 until size) if (this[i] < smallest) {
16+
smallest = this[i]
17+
index = i
18+
}
19+
return index
20+
}
21+
22+
23+
fun main(args: Array<String>) {
24+
val array = arrayListOf(0, 2, 5, 1, 8, 23, 31, 21, 93, 213, 31, 11, 1512, 231, 341, 516, 132, 322, 421, 643)
25+
print("sort: ${array.selectionSort()}")
26+
}

0 commit comments

Comments
 (0)