Last active
July 20, 2022 23:15
-
-
Save mbove77/1158440a780d33d71e33540a55b71726 to your computer and use it in GitHub Desktop.
Bubble sort with recursion implemented in kotlin
This file contains 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
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