Skip to content

Instantly share code, notes, and snippets.

@AafaaqAli
Created July 5, 2022 19:30
Show Gist options
  • Save AafaaqAli/5909288426187e92ce99609a4ef3cd5f to your computer and use it in GitHub Desktop.
Save AafaaqAli/5909288426187e92ce99609a4ef3cd5f to your computer and use it in GitHub Desktop.
Bubble Sort in Kotlin
/**
* 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(bubbleSort(unsortedArray))
}
//gets input of unsorted Array and returns sorted Array
fun bubbleSort(array: ArrayList<Int>): ArrayList<Int>{
//if array is empty or array.size is 1 simpley return the array
if(array.isEmpty() || array.size == 1){
return array
}else{
for(indexA in 0 until array.size - 1){
for(indexB in 0 until (array.size - indexA -1)){
if(array[indexB] > array[indexB + 1]){
//swap values, from array
swap(array, indexB, indexB + 1)
}
}
}
}
//after sorting return the array
return array
}
fun swap(array: ArrayList<Int>, indexA: Int, indexB: Int){
var tempValue = array[indexA]
array[indexA] = array[indexB]
array[indexB] = tempValue
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment