Skip to content
Prev Previous commit
Next Next commit
simplfy bubble sort implemtation
  • Loading branch information
Ken Power committed Oct 3, 2018
commit ea1368d120c7d15b6857f35e82ae51bef8dc44ce
32 changes: 18 additions & 14 deletions contents/bubble_sort/code/scala/bubble_sort.scala
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
object BubbleSort {
def bubbleBiggest(unprocessed: List[Int], notBiggest: List[Int] = List()): List[Int] =
unprocessed match {
case a :: b :: tail =>
if (a > b) bubbleBiggest(a :: tail, b :: notBiggest)
else bubbleBiggest(b :: tail, a :: notBiggest)
case a :: Nil => a :: notBiggest
case Nil => unprocessed

def bubbleUpLargestToTheEnd(list: List[Int]): List[Int] =
list match {
case first :: second :: tail if first > second => second :: bubbleUpLargestToTheEnd(first :: tail)
case first :: second :: tail => first :: bubbleUpLargestToTheEnd(second :: tail)
case _ => list
}

def bubbleSort(unsorted: List[Int], sorted: List[Int] = List()): List[Int] =
bubbleBiggest(unsorted) match {
case m :: us => bubbleSort(us, m :: sorted)
case _ => sorted
def bubbleSort(list: List[Int]): List[Int] =
bubbleUpLargestToTheEnd(list) match {
case unsorted :+ largest => bubbleSort(unsorted) :+ largest
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just for curiosity, is the :+ operator O(n) or O(1)? I ask because in Haskell it would be O(n), which is not ideal.

Copy link
Contributor Author

@kenpower kenpower Oct 3, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your feedback @jiegillet.

Not sure but I suspect it is O(n) given how the List is implemented. I've played around with getting rid of :+ in the pattern matcher but all my attempts are either less readable, less elegant or less idiomatic.

If I were concerned about performance, I would bring back the tail recursive approach from my first version, but that is definitely more difficult to read. Also we could implement using Array, but then the solution starts to look like an imperative approach.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose we are really not concerned with performance here, so the more readable, the better.

case _ => list
}

def main(args: Array[String]): Unit =
println(bubbleSort(List(9, 2, 0, 5, 3, 8, 1, 9, 4, 0, 7, 0, 9, 9, 0)))
}

def main(args: Array[String]): Unit = {
val unsorted = List(9, 2, 0, 5, 3, 8, 1, 9, 4, 0, 7, 0, 9, 9, 0)

println("Unsorted list is " + unsorted)
println(" Sorted list is " + bubbleSort(unsorted))
}
}