Kotlin Program to Implement Bubble Sort

Kotlin Program to Implement Bubble Sort

Sorting is one of the most common tasks in programming, and among the many sorting algorithms out there, Bubble Sort is often the first one beginners learn. Bubble Sort is a simple algorithm that repeatedly steps through a list, compares neighboring elements, and swaps them if they are in the wrong order. This process continues until the list is completely sorted. It’s called “Bubble Sort” because smaller elements “bubble” to the top (or the beginning of the list), just like bubbles rising in water.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

In real-world applications, Bubble Sort isn’t the fastest algorithm for large datasets, but it plays a big role in helping new programmers understand how sorting works at a basic level. It’s great for teaching fundamental ideas like nested loops, condition checking, and array manipulation. Many developers start with Bubble Sort before moving on to more advanced techniques like Merge Sort, Quick Sort, or Heap Sort. In this article, we’ll explore different ways to implement Bubble Sort in Kotlin — using loops, recursion, and a few clever variations. Each example is written simply, so you can follow along even if you’re just starting out with Kotlin programming.

Program 1: Basic Bubble Sort using Loops

This is the simplest version of the Bubble Sort algorithm. It uses two for loops to compare and swap elements until the array is sorted.

fun main() {

    val numbers = intArrayOf(5, 2, 9, 1, 5, 6)

    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        for (j in 0 until numbers.size - i - 1) {

            if (numbers[j] > numbers[j + 1]) {

                val temp = numbers[j]
                numbers[j] = numbers[j + 1]
                numbers[j + 1] = temp

            }

        }

    }

    println("Sorted Array: ${numbers.joinToString()}")

}

In this version, the program goes through the array multiple times. During each pass, the biggest number among the unsorted ones moves to the end, just like a bubble rising to the surface. By the time the outer loop finishes, the array is sorted. This is an easy way to understand how sorting works step by step.

Program 2: Optimized Bubble Sort

This version improves the previous one by adding a flag that checks if any swapping happened during a pass. If no swapping occurs, it means the array is already sorted, so the program stops early.

fun main() {

    val numbers = intArrayOf(4, 3, 2, 1)
    
    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        var swapped = false

        for (j in 0 until numbers.size - i - 1) {

            if (numbers[j] > numbers[j + 1]) {

                val temp = numbers[j]
                numbers[j] = numbers[j + 1]
                numbers[j + 1] = temp
                swapped = true

            }

        }

        if (!swapped) break

    }

    println("Sorted Array: ${numbers.joinToString()}")

}

Here, the swapped variable helps improve performance. If during a pass no elements were swapped, the algorithm knows the array is sorted and stops looping early. This makes it faster in best-case scenarios like when the input array is already sorted. Beginners can learn from this version how small improvements can make a big difference in efficiency.

Program 3: Bubble Sort Using While Loop

Instead of using a for loop, this version of Bubble Sort uses a while loop. It works the same way but shows how flexible Kotlin can be when working with different loop structures.

fun main() {

    val numbers = intArrayOf(7, 3, 8, 2, 9)

    println("Original Array: ${numbers.joinToString()}")

    var n = numbers.size
    var swapped: Boolean

    do {

        swapped = false

        for (i in 0 until n - 1) {

            if (numbers[i] > numbers[i + 1]) {

                val temp = numbers[i]
                numbers[i] = numbers[i + 1]
                numbers[i + 1] = temp
                swapped = true

            }

        }

        n--

    } while (swapped)

    println("Sorted Array: ${numbers.joinToString()}")

}

This version is especially good for those who want to practice using do-while loops in Kotlin. The algorithm keeps looping until no swaps occur. Each pass shortens the range of elements being checked, improving the performance slightly as sorting progresses.

Program 4: Recursive Bubble Sort

This approach uses recursion instead of loops. The function keeps calling itself until the array becomes sorted.

fun bubbleSortRecursive(arr: IntArray, n: Int) {

    if (n == 1) return

    for (i in 0 until n - 1) {

        if (arr[i] > arr[i + 1]) {

            val temp = arr[i]
            arr[i] = arr[i + 1]
            arr[i + 1] = temp

        }

    }

    bubbleSortRecursive(arr, n - 1)

}

fun main() {

    val numbers = intArrayOf(10, 3, 15, 7, 8, 23, 98, 29)

    println("Original Array: ${numbers.joinToString()}")

    bubbleSortRecursive(numbers, numbers.size)

    println("Sorted Array: ${numbers.joinToString()}")

}

In this version, the algorithm uses recursion to repeatedly sort smaller parts of the array. Each call of the function sorts the array except the last element, which is already in its correct place. This program is great for understanding how recursion works in Kotlin, and how a problem can be broken down into smaller subproblems until it’s fully solved.

Program 5: Bubble Sort in Descending Order

Sometimes, you might want to sort numbers from largest to smallest. This variation does exactly that by simply changing the comparison condition.

fun main() {

    val numbers = intArrayOf(1, 4, 2, 9, 6)

    println("Original Array: ${numbers.joinToString()}")

    for (i in numbers.indices) {

        for (j in 0 until numbers.size - i - 1) {

            if (numbers[j] < numbers[j + 1]) {

                val temp = numbers[j]
                numbers[j] = numbers[j + 1]
                numbers[j + 1] = temp

            }

        }

    }

    println("Sorted in Descending Order: ${numbers.joinToString()}")

}

Here, by flipping the comparison sign from > to <, the Bubble Sort now arranges numbers in descending order. This is a nice example to show how small changes in logic can completely change the output. Beginners can use this to experiment and learn about flexibility in algorithms.

Frequently Asked Questions (FAQ)

This section answers some of the most common questions beginners have about Bubble Sort in Kotlin.

Q1: What is Bubble Sort in Kotlin?
Bubble Sort is a simple sorting algorithm that repeatedly compares and swaps adjacent elements until the entire array is sorted.

Q2: Is Bubble Sort efficient for large datasets?
No, Bubble Sort is not efficient for large datasets because it has a time complexity of O(n²). It’s best for small lists or for learning purposes.

Q3: Can Bubble Sort sort strings or characters in Kotlin?
Yes, it can. You just need to modify the array type to CharArray or Array<String> and adjust the comparison logic accordingly.

Q4: What is the main difference between recursive and iterative Bubble Sort?
Iterative Bubble Sort uses loops, while recursive Bubble Sort calls the same function repeatedly until the array is sorted. Both achieve the same result but in different ways.

Q5: How can I make Bubble Sort faster?
You can improve performance by adding a flag to check if any swapping happened during a pass, as shown in the optimized version. If no swaps occur, the loop can stop early.

Conclusion

Bubble Sort might not be the fastest sorting algorithm, but it’s one of the best ways to understand how sorting works behind the scenes. It teaches important ideas like iteration, condition checking, and swapping values. In Kotlin, Bubble Sort is easy to implement and helps you build a strong foundation for learning more complex algorithms later on.

Whether you use loops or recursion, the key is to practice writing and modifying the code until you truly understand each step. The more you experiment, the stronger your problem-solving skills will become. So, open your Kotlin editor, try out these programs, and watch how those numbers neatly fall into order — just like bubbles rising to the top!

Scroll to Top