Skip to content

Instantly share code, notes, and snippets.

@alaz
Created May 24, 2020 12:23
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 alaz/e6d0bdbd7efee3e3f45a04a4e6ae0856 to your computer and use it in GitHub Desktop.
Save alaz/e6d0bdbd7efee3e3f45a04a4e6ae0856 to your computer and use it in GitHub Desktop.
def radixSort(arr: Seq[Int]): Seq[Int] = {
def fn(state: Seq[Int], d: Int): Seq[Int] = {
val ten_power_d = Iterator.fill(d)(10).product
val buckets = state.groupBy(_ / ten_power_d % 10).toMap
buckets.keys.toSeq.sorted.foldLeft(Seq.empty[Int]) { case (acc, i) =>
acc ++ buckets(i)
}
}
val digits = Iterator.iterate(arr) {
_.map(_ / 10)
}.takeWhile {
_.exists(_ > 0)
}.size
0.to(digits).foldLeft(arr)(fn)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment