Skip to content

Instantly share code, notes, and snippets.

@akihiro4chawon
Forked from rrgroovy/bubbleSort.groovy
Created November 12, 2011 15:24
Show Gist options
  • Save akihiro4chawon/1360677 to your computer and use it in GitHub Desktop.
Save akihiro4chawon/1360677 to your computer and use it in GitHub Desktop.
Reinvention of the Wheel Series, "Bubble Sort in Scalaz".
import scalaz._
import Scalaz._
object Bubble {
def bubbleSort[A: Order](xs: List[A]) = xs.unfold[Stream, A] {
_.foldr[Option[(A, List[A])]](none){ (x, zs) =>
zs.fold({case (y, ys) => (x lt y).fold((x, y::ys), (y, x::ys))}, (x, nil[A])).some
}
}
}
// 泡が浮く種類のバブルソート
// 遅延評価で必要な数だけ浮いてくるので、先頭数個取るだけなら高速
scala> val s = Bubble.bubbleSort((100000 to 1 by -1).toList)
s: Stream[Int] = Stream(1, ?)
scala> s take 10 print
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, empty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment