0
0
KotlinProgramBeginner · 2 min read

Kotlin Program for Bubble Sort with Example and Explanation

A Kotlin program for bubble sort uses nested loops to repeatedly swap adjacent elements if they are in the wrong order, like 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

Input[5, 3, 8, 4, 2]
Output[2, 3, 4, 5, 8]
Input[1, 2, 3, 4, 5]
Output[1, 2, 3, 4, 5]
Input[]
Output[]
🧠

How to Think About It

To sort a list using bubble sort, think of repeatedly passing through the list and comparing each pair of neighbors. If the left one is bigger, swap them. Keep doing this until no swaps are needed, meaning the list is sorted.
📐

Algorithm

1
Get the input array.
2
Repeat from the first element to the last unsorted element:
3
Compare each pair of adjacent elements.
4
If the left element is greater than the right, swap them.
5
After each pass, the largest unsorted element moves to its correct position.
6
Repeat until the entire array is sorted.
💻

Code

kotlin
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 = "]"))
}
Output
[2, 3, 4, 5, 8]
🔍

Dry Run

Let's trace the array [5, 3, 8, 4, 2] through the bubble sort code.

1

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]

2

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]

3

Third pass comparisons and swaps

Compare 3 and 4, no swap; compare 4 and 2, swap -> [3, 2, 4, 5, 8]

4

Fourth pass comparisons and swaps

Compare 3 and 2, swap -> [2, 3, 4, 5, 8]

PassArray 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

Optimized Bubble Sort with Early Exit
kotlin
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 = "]"))
}
Stops early if no swaps happen in a pass, improving performance on nearly sorted arrays.
Using Kotlin's Built-in Sort
kotlin
fun main() {
    val arr = intArrayOf(5, 3, 8, 4, 2)
    arr.sort()
    println(arr.joinToString(prefix = "[", postfix = "]"))
}
Uses Kotlin's built-in efficient sort method, which is faster and simpler but hides the sorting logic.

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.

ApproachTimeSpaceBest For
Standard Bubble SortO(n²)O(1)Learning and small arrays
Optimized Bubble SortO(n) best, O(n²) worstO(1)Nearly sorted arrays
Kotlin Built-in SortO(n log n)O(n) or O(1) depending on implementationAll practical sorting needs
💡
Use an early exit flag in bubble sort to stop if the array is already sorted and save time.
⚠️
Beginners often forget to reduce the inner loop range each pass, causing unnecessary comparisons.