Kotlin Program for Bubble Sort with Example and Explanation
for (i in 0 until n-1) { for (j in 0 until n-i-1) { if (arr[j] > arr[j+1]) { val temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp } } } to sort the array.Examples
How to Think About It
Algorithm
Code
fun bubbleSort(arr: IntArray) {
val n = arr.size
for (i in 0 until n - 1) {
for (j in 0 until n - i - 1) {
if (arr[j] > arr[j + 1]) {
val temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
}
}
}
}
fun main() {
val arr = intArrayOf(5, 3, 8, 4, 2)
bubbleSort(arr)
println(arr.joinToString(prefix = "[", postfix = "]"))
}Dry Run
Let's trace the array [5, 3, 8, 4, 2] through the bubble sort code.
First pass comparisons and swaps
Compare 5 and 3, swap -> [3, 5, 8, 4, 2]; compare 5 and 8, no swap; compare 8 and 4, swap -> [3, 5, 4, 8, 2]; compare 8 and 2, swap -> [3, 5, 4, 2, 8]
Second pass comparisons and swaps
Compare 3 and 5, no swap; compare 5 and 4, swap -> [3, 4, 5, 2, 8]; compare 5 and 2, swap -> [3, 4, 2, 5, 8]
Third pass comparisons and swaps
Compare 3 and 4, no swap; compare 4 and 2, swap -> [3, 2, 4, 5, 8]
Fourth pass comparisons and swaps
Compare 3 and 2, swap -> [2, 3, 4, 5, 8]
| Pass | Array State After Pass |
|---|---|
| 1 | [3, 5, 4, 2, 8] |
| 2 | [3, 4, 2, 5, 8] |
| 3 | [3, 2, 4, 5, 8] |
| 4 | [2, 3, 4, 5, 8] |
Why This Works
Step 1: Repeated comparisons
The code uses nested loops to compare each pair of neighbors with if (arr[j] > arr[j + 1]) and swaps them if needed.
Step 2: Largest element moves right
After each outer loop pass, the largest unsorted element moves to its correct position at the end.
Step 3: Sorting completes when no swaps needed
Repeating passes ensures all elements bubble up to their sorted positions, resulting in a fully sorted array.
Alternative Approaches
fun bubbleSortOptimized(arr: IntArray) {
val n = arr.size
for (i in 0 until n - 1) {
var swapped = false
for (j in 0 until n - i - 1) {
if (arr[j] > arr[j + 1]) {
val temp = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = temp
swapped = true
}
}
if (!swapped) break
}
}
fun main() {
val arr = intArrayOf(1, 2, 3, 4, 5)
bubbleSortOptimized(arr)
println(arr.joinToString(prefix = "[", postfix = "]"))
}fun main() {
val arr = intArrayOf(5, 3, 8, 4, 2)
arr.sort()
println(arr.joinToString(prefix = "[", postfix = "]"))
}Complexity: O(n²) time, O(1) space
Time Complexity
Bubble sort uses two nested loops over the array, making it O(n²) in the worst and average cases.
Space Complexity
It sorts the array in place, so it uses only O(1) extra space.
Which Approach is Fastest?
The optimized bubble sort can be faster on nearly sorted data, but built-in sort methods are generally much faster overall.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Standard Bubble Sort | O(n²) | O(1) | Learning and small arrays |
| Optimized Bubble Sort | O(n) best, O(n²) worst | O(1) | Nearly sorted arrays |
| Kotlin Built-in Sort | O(n log n) | O(n) or O(1) depending on implementation | All practical sorting needs |