Skip to content
This repository has been archived by the owner on Oct 6, 2021. It is now read-only.

Selection Sort for Kotlin (#51) #283

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Kotlin/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ Format: -[Program name](name of the file)

[Row with minimum number of 1's](./min_number_of_1.kt)

[Selection Sort](https://github.com/shauryam-exe/DS-Algo-Zone/blob/main/Kotlin/SelectionSort.kt) <br />

[Quick Sort](./QuickSort.kt)

[Fibonacci](./fibonacci.kt)
Expand Down
30 changes: 30 additions & 0 deletions Kotlin/SelectionSort.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
fun main(args: Array<String>) {
//Input the array in the format num1 num2 num3 num4 etc
print("Enter the elements for the Array: ")
var inputArray = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray()

var sortedArray = selectionSort(inputArray)
println(sortedArray.contentToString())
}

fun selectionSort(arr: IntArray): IntArray {
for (i in arr.lastIndex downTo 0) {
var max = arr[0]
var maxIndex = 0
for (j in 0..i) {
if (arr[maxIndex]<arr[j])
maxIndex = j
}
val temp = arr[maxIndex]
arr[maxIndex] = arr[i]
arr[i] = temp
}
return arr
}

//Sample
//Input: Enter the elements for the Array: 64 23 -12 -5 0 2 89 20 100 32 650 -230 130
//Output: [-230, -12, -5, 0, 2, 20, 23, 32, 64, 89, 100, 130, 650]

//Time Complexity: Worst Case: O(n^2) Best Case: O(n^2)
//Space Complexity: O(1)