Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of an array are checked and swapped if they are in wrong order and this process is repeated until we get a sorted array.
The steps of performing a bubble sort are:
Bubble sort, as such serves no benefit from the efficiency's point of view. Yet, it is taught in computer science courses, just for exploration of sorting techniques.
O(n2)
sorting algorithms, which makes it quite inefficient for sorting large data volumes.O(n) time
, but requires at least 2 passes through the data.
swap
variable becomes false.
var swap = true
while(swap){
last but one +1 -> last index
for(i in 0 until arr.size-1){
index
with index+1
, if element at index is bigger than element at index+1, then swap the elements
if(arr[i] > arr[i+1]){
val temp = arr[i]
arr[i] = arr[i+1]
arr[i + 1] = temp
swap = true
}
Complete kotlin example for Bubble sort in Kotlin
fun bubbleSort(arr:IntArray):IntArray{
var swap = true
while(swap){
swap = false
for(i in 0 until arr.size-1){
if(arr[i] > arr[i+1]){
val temp = arr[i]
arr[i] = arr[i+1]
arr[i + 1] = temp
swap = true
}
}
}
return arr
}
fun main(args: Array<String>) {
val list = bubbleSort(intArrayOf(2,15,1,8,4))
for (k in list) print("$k ")
}
This article is written by Pavan, who is serving notice period in an MNC, Bangalore. He thought, let the articles speak rather than his image. He is also the same person who created the reporter for Protractor Jasmine