Bubble Sort Algorithm Program in Kotlin

In this article, we will learn to write a Kotlin program to sort an array using Bubble Sort algorithm. Bubble sort is also known as Sinking Sort Algorithm. Bubble Sort is an array sorting algorithm. Best case time complexity of Bubble Sort is O(n) and worst case time complexity is O(n^2).

Source Code:
fun main(args: Array<String>)
{
    val arr = intArrayOf(3, 5, -2, 1, -3, 2, -1, -5, -4, 4)
    println("Array sequence before Bubble Sort:")

    for (i in arr.indices) {
        print(arr[i].toString() + " ")
    }
    println()
    bubbleSort(arr)
    println("Array sequence after Bubble Sort")

    for (i in arr.indices) {
        print(arr[i].toString() + " ")
    }
}

internal fun bubbleSort(arr: IntArray)
{
    val n = arr.size
    var temp = 0
    for (i in 0 until n) {
        for (j in 1 until n - i) {
            if (arr[j - 1] > arr[j]) {
                temp = arr[j - 1]
                arr[j - 1] = arr[j]
                arr[j] = temp
            }
        }
    }
}
Output:
Array sequence before  Bubble Sort:
3 5 -2 1 -3 2 -1 -5 -4 4
Array sequence after Bubble Sort
-5 -4 -3 -2 -1 1 2 3 4 5

Description:
In the above program, it repeatedly steps through the list to be sorted, which compares each pair of adjacent items and swaps them if they are in the wrong order. These steps will be repeated until no swaps are needed, which means that the list is sorted. In the above program, we have used bubbleSort() method to sort the array.

Also Read: Linear Search Algorithm Program in Kotlin

Post a Comment

0 Comments