Skip to content

Instantly share code, notes, and snippets.

@dakatsuka
Last active December 20, 2015 14:32
Show Gist options
  • Save dakatsuka/7258b9da61ae208f31a6 to your computer and use it in GitHub Desktop.
Save dakatsuka/7258b9da61ae208f31a6 to your computer and use it in GitHub Desktop.
バブルソート
def bswap[A](xs: List[A])(implicit o: A => Ordered[A]): List[A] = xs.foldRight(List.empty[A]) {
case (x, y) if y.isEmpty => List(x)
case (x, y) if x > y.head => y.head :: x :: y.tail
case (x, y) => x :: y
}
def bsort[A](xs: List[A])(implicit o: A => Ordered[A]): List[A] = bswap(xs) match {
case x :: t => x :: bsort(t)
case Nil => List.empty
}
println(bsort(List(5,4,2,1,3)))
println(bsort(List(4,6,9,8,3,5,1,7,2)))
println(bsort(List(2.3, 0.21, 1.5, 3.2)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment