Welcome to BigData School that can get you hired on Small startups or big Product based companies.Are you tired of 30-40 hours of theoritical bigdata courses in the market. Welcome to 240+ hours of Bigdata training. Just subscribe to our popup to get access to our 80+hours of course absolutely free.Try them out and you can join our further course once you are happy with our Demos.

Bubble-Sort

Big Data    On Thursday 22nd of June 2017 12:10:06 PM By Suraz Ghimire
Here is the  implementation of bubble sort.

TimeComplexity: O(n2)
Space Complexity : O(1)
package sorting

package sorting

object BubbleSort {
def sort(arr: Array[Int]): Unit = {

import scala.util.control.Breaks._
breakable {
for (i <- 0 until arr.length) {
var swap = false
for (j <- 0 until arr.length - i - 1) {
if (arr(j) > arr(j + 1)) {
val temp = arr(j)
arr(j) = arr(j + 1)
arr(j + 1) = temp
swap = true
}
}
if (!swap) break
}
}
}

def main(args: Array[String]): Unit = {
val arr=Array(25,15,30,5,10,20 )
sort(arr)
arr.foreach(println)
}
}


Output:
5
10
15
20
25
30

Note: In this example, we are breaking the loop, in case we dont go inside the inner loop for a swap. If no swapping is required then the arra is already sorted.

About Author

Suraz Ghimire