Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active January 2, 2016 18:43
Show Gist options
  • Select an option

  • Save sshark/a4b6d420514d74d4ede3 to your computer and use it in GitHub Desktop.

Select an option

Save sshark/a4b6d420514d74d4ede3 to your computer and use it in GitHub Desktop.
Bubble sort functional. Stop if list is sorted without go through all possible combinations
import scala.annotation.tailrec
def bubbleSort(l: Seq[Int]): Seq[Int] = {
def isSorted(s: Seq[Int]) = ((false, Int.MinValue) /: s){
case ((flag, prev), current) =>
if (prev <= current) (true, current) else (false, Int.MaxValue)
}._1
def _bubbleSort(m: Seq[Int]): Seq[Int] = m match {
case x +: y +: Nil => if (x > y) y +: x +: Nil else x +: y +: Nil
case x +: y +: zs =>
if (x > y) y +: _bubbleSort(x +: zs)
else x +: _bubbleSort(y +: zs)
}
@tailrec
def goSort(s: Seq[Int]): Seq[Int] = if (isSorted(s)) s
else goSort(_bubbleSort(s))
goSort(_bubbleSort(l))
}
bubbleSort(Seq(-1000, 101, 30, 4, -100, 1, 4, 3, 1, 2, -100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment