bubble sort


See On Github

Data

Source Code


class BubbleSort {

  def bubbleSort[T](arrayToBeSorted: Array[T])(implicit o: Ordering[T]): Array[T] = {

    import o._
    val consecutiveIndices = (arrayToBeSorted.indices, arrayToBeSorted.indices drop 1).zipped
    var hasChanged = true

    while (hasChanged) {

      hasChanged = false
      consecutiveIndices foreach { (i1, i2) =>

        if (arrayToBeSorted(i1) > arrayToBeSorted(i2)) {
          hasChanged = true
          val temporaryVariable = arrayToBeSorted(i1)
          arrayToBeSorted(i1) = arrayToBeSorted(i2)
          arrayToBeSorted(i2) = temporaryVariable
        }
      }
    }

    arrayToBeSorted
  }
}

import org.scalatest.{Matchers, FunSuite}

class BubbleSortTest extends FunSuite with Matchers {

  test("Bubble Sort should sort") {
    val objectForBubbleSort = new BubbleSort

    objectForBubbleSort.bubbleSort(Array(11,1,4,22)) should be(Array(1,4,11,22))
    objectForBubbleSort.bubbleSort(Array(1,2,3,4,5)) should be(Array(1,2,3,4,5))
  }
}