Skip to content

Instantly share code, notes, and snippets.

@mbove77
Last active July 20, 2022 23:15
Show Gist options
  • Save mbove77/1158440a780d33d71e33540a55b71726 to your computer and use it in GitHub Desktop.
Save mbove77/1158440a780d33d71e33540a55b71726 to your computer and use it in GitHub Desktop.
Bubble sort with recursion implemented in kotlin
fun bubbleSort(inputArray: Array<Int>, nextIterIndex: Int = inputArray.size): Array<Int> {
// This print is for see the interactions in sort algorithm
println("iteration number ${inputArray.size - nextIterIndex+1}")
val lastIndex = nextIterIndex -1
var isSorted = true
for (i in 0 until lastIndex) {
val currentItem = inputArray[i]
val nextItem = inputArray[i+1]
if (currentItem > nextItem) {
inputArray[i] = nextItem
inputArray[i+1] = currentItem
isSorted = false
}
}
return if (isSorted) {
inputArray
} else {
bubbleSort(inputArray, lastIndex)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment