Skip to content

Commit 7411296

Browse files
committed
Merge pull request kennyledet#84 from lichtsprung/master
added bogo sort in scala
2 parents 5f2c7f6 + 47f51cd commit 7411296

2 files changed

Lines changed: 44 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
object bogo_sort {
2+
3+
def sort[T: Ordering](values: Array[T]): Array[T] = {
4+
values.permutations foreach {
5+
p
6+
if (isSorted(p)) {
7+
return p
8+
}
9+
}
10+
values
11+
}
12+
13+
def sort_v2[T: Ordering](values: Array[T]): Array[T] = {
14+
values.permutations.find(_.deep == values.sorted.deep).getOrElse(values)
15+
}
16+
17+
private def isSorted[T: Ordering](values: Array[T]): Boolean = {
18+
val ord = Ordering[T]
19+
import ord._
20+
21+
for (i 1 until values.size) {
22+
if (values(i - 1) > values(i)) {
23+
return false
24+
}
25+
}
26+
true
27+
}
28+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import org.scalatest.{ Matchers, FlatSpec }
2+
import bogo_sort._
3+
4+
class bogo_sort_test extends FlatSpec with Matchers {
5+
val values = Array(1, 17, -4, 2)
6+
7+
"Bogo Sort" should "sort an array of Ints" in {
8+
val sorted = sort(values)
9+
sorted should contain inOrder (-4, 1, 2, 17)
10+
}
11+
12+
"Bogo Sort V2" should "sort an array of Ints by looking for the sorted array in the iterator of all permutations " in {
13+
val sorted = sort_v2(values)
14+
sorted should contain inOrder (-4, 1, 2, 17)
15+
}
16+
}

0 commit comments

Comments
 (0)