Search code examples
scalaintellij-ideabubble-sort

Can anyone explain the following Scala code?


I have to describe BubbleSort in Scala and I tested it with this code. But I don't know exactly what each of the functions does.

object BubbleSort {
  def sort(list: List[Int]): List[Int] = list match {
    case List() => List()
    case head :: tail => compute(head, sort(tail))
  }

  def compute(data: Int, dataSet: List[Int]): List[Int] = dataSet match {
    case List() => List(data)
    case head :: tail => if (data <= head) data :: dataSet else head :: compute(data, tail)
  }

  def main(args: Array[String]) {
    val list = List(3, 12, 43, 23, 7, 1, 2, 0)
    println(sort(list))
  }
}

Can anyone explain it to me?


Solution

  • Look how your functions work starting from the last element

    sort(List()) // List()
    compute(0, List()) // List(0)
    sort(List(0))      // List(0)
    compute(2, List(0)) // List(0, 2)
    sort(List(2, 0))    // List(0, 2)
    compute(1, List(0, 2)) // List(0, 1, 2)
    sort(List(1, 0, 2))    // List(0, 1, 2)
    compute(7, List(0, 1, 2)) // List(0, 1, 2, 7)
    sort(List(7, 0, 1, 2))    // List(0, 1, 2, 7)
    compute(23, List(0, 1, 2, 7)) // List(0, 1, 2, 7, 23)
    sort(List(23, 0, 1, 2, 7))    // List(0, 1, 2, 7, 23)
    compute(43, List(0, 1, 2, 7, 23)) // List(0, 1, 2, 7, 23, 43)
    sort(List(43, 0, 1, 2, 7, 23))    // List(0, 1, 2, 7, 23, 43)
    compute(12, List(0, 1, 2, 7, 23, 43)) // List(0, 1, 2, 7, 12, 23, 43)
    sort(List(12, 0, 1, 2, 7, 23, 43))    // List(0, 1, 2, 7, 12, 23, 43)
    compute(3, List(0, 1, 2, 7, 12, 23, 43)) // List(0, 1, 2, 3, 7, 12, 23, 43)
    sort(List(3, 0, 1, 2, 7, 12, 23, 43))    // List(0, 1, 2, 3, 7, 12, 23, 43)
    

    compute pushes the element ("bubble") till proper place.