Skip to content

Instantly share code, notes, and snippets.

@arnaudoff
Created January 25, 2018 21:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arnaudoff/915b1100901344ca22ad0997b175b123 to your computer and use it in GitHub Desktop.
Save arnaudoff/915b1100901344ca22ad0997b175b123 to your computer and use it in GitHub Desktop.
object BubbleSort {
def sort(xs: List[Int]) = {
def bsort(xs: List[Int], current: Int, dest: Int): List[Int] = {
dest match {
case 0 => xs
case _ if (dest == current) => bsort(xs, 0, dest - 1)
case _ =>
if (xs(current) > xs(current + 1)) {
var tmp = xs(current + 1)
xs(current + 1) = xs(current)
xs(current) = tmp
}
bsort(xs, current + 1, dest)
}
}
bsort(xs, 0, xs.length - 1)
}
}
@PlamenNeshkov
Copy link

PlamenNeshkov commented Jan 25, 2018

def sort(items: List[Int]): List[Int] = {
  def bSort(xs: List[Int], unsorted: List[Int] = Nil, sorted: List[Int] = Nil) = xs match {
    case x :: Nil =>
      if (unsorted.isEmpty) x :: sorted
      else bSort(unsorted, Nil, x :: sorted)
    case x :: y :: zs =>
      if (x > y) bSort(x :: zs, y :: unsorted, sorted)
      else bSort(y :: zs, x :: unsorted, sorted)
  }
  bSort(items)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment