Quick actions

cmd+k|ctrl+k

Navigation

Languages

Bubble Sort

Snippet info

Language

Scala

Visibility

public

Author

devernul

Created

2018-12-08T08:08:47Z

Updated

2018-12-08T08:08:47Z

object Main extends App {
        def bubleSort(arr: Array[Int]) = { //O(n2), O(1) space
            for (i <- 0 until arr.size) {
                for (j <- 0 until arr.size-1) {
                    if (arr(j) > arr(j+1)) {
                        val temp = arr(j+1)
                        arr(j+1) = arr(j)
                        arr(j) = temp
                    }
                }
            }
            arr
        }
        
      def bubbleSort(array: Array[Int]) = {
        def bubbleSortRecursive(array: Array[Int], current: Int, to: Int): Array[Int] = {
            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)
      }
   
    println(bubleSort(Array(1,4,3,6,-2,3,6,38,49,2,900,5,7,1,4,3,6,-2,3,6,38,49,2,900,5,7)).toList)
    println(bubbleSort(Array(1,4,3,6,-2,3,6,38,49,2,900,5,7,1,4,3,6,-2,3,6,38,49,2,900,5,7)).toList)
}
INFO