flying3615
8/27/2017 - 11:52 PM

bubble sort & quick sort in scala

bubble sort & quick sort in scala

object BubbleSort extends Sortable {
  override def sort(input: Array[Int]) = {
    if (input.isEmpty) new Array[Int](0)
    for (i <- 0 until input.length - 1; j <- 0 until input.length - 1 - i) {
      if (input(j) > input(j + 1)) {
        val temp = input(j)
        input(j) = input(j + 1)
        input(j + 1) = temp
      }
    }
    input
  }
}


object QuickSort extends Sortable {
  override def sort(input: Array[Int]): Array[Int] = {
    if (input.length < 2) input
    else {
      val pivot = input(input.length / 2)
      sort(input filter (_ < pivot)) ++ (input filter (_ == pivot)) ++ sort(input filter (_ > pivot))
    }
  }
}