Created
July 5, 2022 18:39
-
-
Save AafaaqAli/7c72210836fecc6f4767258beb0df4be to your computer and use it in GitHub Desktop.
Selection Sort in 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
/** | |
* Complexity O(n^2) | |
*/ | |
/** | |
* Unsorted Data Source | |
*/ | |
var unsortedArray: ArrayList<Int> = arrayListOf(45,7,3,6,12,657,568,23412,3,46,647,234,7687,686,235,564,768568,345,23,1,23,3,46,7,8,945,34) | |
fun main() { | |
//print out the sorted array returned from function | |
System.out.print(selectionSort(unsortedArray)) | |
} | |
//gets input of unsorted Array and returns sorted Array | |
fun selectionSort(array: ArrayList<Int>): ArrayList<Int>{ | |
//Selection sort uses 2 Integers, For saving the lowest value found in each iteration, and its index | |
var lowerValue: Int = 0 | |
var lowerValueIndex: Int = 0 | |
//if array is empty simpley return the array | |
if(array.isEmpty()){ | |
return array | |
}else{ | |
//loop through the array until last index, first loop will iterate the counter for each element | |
array.forEachIndexed{indexA, _ -> | |
//each element on every index will be considered as lowest and then be compared with each element until finds least element | |
lowerValue = array[indexA] | |
//loop entire array starting from [sorted arraya] + 1 until end until least value is found | |
for(indexB in indexA until array.size){ | |
if(lowerValue > array[indexB]){ | |
lowerValue = array[indexB] | |
lowerValueIndex = indexB | |
} | |
} | |
//swap values, from array | |
swap(array, indexA, lowerValueIndex, lowerValue) | |
} | |
//after sorting return the array | |
return array | |
} | |
} | |
fun swap(array: ArrayList<Int>, indexA: Int, indexB: Int, lowerVal: Int){ | |
var tempValue = array[indexA] | |
array[indexA] = lowerVal | |
array[indexB] = tempValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment