Bubble sort is a simple sorting algorithm that repeatedly iterates through the array, compares adjacent elements and swaps them if they are in the wrong order. During each pass through the array, the largest element will “bubble” to the end of the unsorted part of the array, so the algorithm gets its name from this behavior. The algorithm continues iterating through the array until no more swaps are needed, which means the array is sorted.
fun bubbleSort(arr: IntArray) {
val n = arr.size
var swapped: Boolean
do {
swapped = false
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
swapped = true
}
}
} while (swapped)
}
The bubbleSort
function takes an array of integers arr
and sorts it in place using the bubble sort algorithm.
The function uses a do-while loop to iterate through the array until no more swaps are needed. The swapped
variable is initially set to false
, and it is set to true
whenever a swap occurs during a pass through the array.
The function uses a for loop to compare adjacent elements of the array and swap them if they are in the wrong order. If an element is greater than its adjacent element, the two elements are swapped. The swapped
variable is set to true
if any swaps occur during the pass through the array.
This process continues until no more swaps occur during a pass through the array, which means the array is sorted.
Bubble sort has a time complexity of O(n^2) in the worst case, where n is the number of elements in the array. This means that the time it takes to sort an array using bubble sort increases quadratically with the size of the array. Bubble sort is not as efficient as other sorting algorithms, such as quicksort or mergesort, but it is simple to understand and implement. Bubble sort is also useful for educational purposes and for sorting small or nearly-sorted arrays.
fun main() {
val arr = intArrayOf(20, 15, 81, 12, 6)
val index = bubbleSort(arr)
for(i in 1 until arr.size)
println(arr[i])
}
fun bubbleSort(arr: IntArray) {
val n = arr.size
var swapped: Boolean
do {
swapped = false
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
swapped = true
}
}
} while (swapped)
}