Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Bogosort/Scala/lichtsprung/bogo_sort.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
object bogo_sort {

def sort[T: Ordering](values: Array[T]): Array[T] = {
values.permutations foreach {
p ⇒
if (isSorted(p)) {
return p
}
}
values
}

def sort_v2[T: Ordering](values: Array[T]): Array[T] = {
values.permutations.find(_.deep == values.sorted.deep).getOrElse(values)
}

private def isSorted[T: Ordering](values: Array[T]): Boolean = {
val ord = Ordering[T]
import ord._

for (i ← 1 until values.size) {
if (values(i - 1) > values(i)) {
return false
}
}
true
}
}
16 changes: 16 additions & 0 deletions Bogosort/Scala/lichtsprung/bogo_sort_test.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import org.scalatest.{ Matchers, FlatSpec }
import bogo_sort._

class bogo_sort_test extends FlatSpec with Matchers {
val values = Array(1, 17, -4, 2)

"Bogo Sort" should "sort an array of Ints" in {
val sorted = sort(values)
sorted should contain inOrder (-4, 1, 2, 17)
}

"Bogo Sort V2" should "sort an array of Ints by looking for the sorted array in the iterator of all permutations " in {
val sorted = sort_v2(values)
sorted should contain inOrder (-4, 1, 2, 17)
}
}