Bubble sort is simplest of all sorting algorithms. We start from the leftmost element of an array and compare two consecutive elements if a[i] > a[i+1] then we swap these two elements, so at the end of whole array scanning we'll have the largest element at the rightmost of the array. Now we repeat the same procedure for all the elements from (0 to n-1), (0 to n-2) ... and so on. The worst case running time of this algorithm will be (n + n-1 + n-2 ... 1) = O(n^2)
10,9,11,5,2 current -> 0, to -> 4
9,10,11,5,2 current -> 1, to -> 4
9,10,11,5,2 current -> 2, to -> 4
9,10,5,11,2 current -> 3, to -> 4
9,10,5,2,11 current -> 4, to -> 4
9,10,5,2,11 current -> 0, to -> 3
9,10,5,2,11 current -> 1, to -> 3
9,5,10,2,11 current -> 2, to -> 3
9,5,2,10,11 current -> 3, to -> 3
9,5,2,10,11 current -> 0, to -> 2
5,9,2,10,11 current -> 1, to -> 2
5,2,9,10,11 current -> 2, to -> 2
5,2,9,10,11 current -> 0, to -> 1
2,5,9,10,11 current -> 1, to -> 1
2,5,9,10,11 current -> 0, to -> 0
Sorted Array -> 2,5,9,10,11
package com.thescalatutorial.examples object BubbleSort { def bubbleSort(array: Array[Int]) = { def bubbleSortRecursive(array: Array[Int], current: Int, to: Int): Array[Int] = { println(array.mkString(",") + " current -> " + current + ", to -> " + to) to match { case 0 => array case _ if(to == current) => bubbleSortRecursive(array, 0, to - 1) case _ => if (array(current) > array(current + 1)) { var temp = array(current + 1) array(current + 1) = array(current) array(current) = temp } bubbleSortRecursive(array, current + 1, to) } } bubbleSortRecursive(array, 0, array.size - 1) } def main(args: Array[String]) { val sortedArray = bubbleSort(Array(10,9,11,5,2)) println("Sorted Array -> " + sortedArray.mkString(",")) } }Running above program will produce following output:
10,9,11,5,2 current -> 0, to -> 4
9,10,11,5,2 current -> 1, to -> 4
9,10,11,5,2 current -> 2, to -> 4
9,10,5,11,2 current -> 3, to -> 4
9,10,5,2,11 current -> 4, to -> 4
9,10,5,2,11 current -> 0, to -> 3
9,10,5,2,11 current -> 1, to -> 3
9,5,10,2,11 current -> 2, to -> 3
9,5,2,10,11 current -> 3, to -> 3
9,5,2,10,11 current -> 0, to -> 2
5,9,2,10,11 current -> 1, to -> 2
5,2,9,10,11 current -> 2, to -> 2
5,2,9,10,11 current -> 0, to -> 1
2,5,9,10,11 current -> 1, to -> 1
2,5,9,10,11 current -> 0, to -> 0
Sorted Array -> 2,5,9,10,11