Skip to content

Commit 73b5714

Browse files
committed
Implemented Bogobogosort in PHP
1 parent ac8580b commit 73b5714

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
<?php
2+
3+
// This one is so comically wrong I had to implement it :) - http://www.dangermouse.net/esoteric/bogobogosort.html
4+
5+
class BogoBogoSort {
6+
7+
public function sortList($numbers_list)
8+
{
9+
while (!$this->isSorted($numbers_list)) {
10+
shuffle($numbers_list);
11+
}
12+
13+
return $numbers_list;
14+
}
15+
16+
public function isSorted($numbers_list)
17+
{
18+
if (count($numbers_list) <= 1) {
19+
return TRUE;
20+
}
21+
22+
$last_element = count($numbers_list) - 1;
23+
24+
$array_copy = $numbers_list;
25+
$array_copy_to_sort = array();
26+
$array_sorted = array();
27+
28+
do {
29+
shuffle($array_copy);
30+
for ($i = 0; $i < count($array_copy) - 1; $i++) {
31+
$array_copy_to_sort[$i] = $array_copy[$i];
32+
}
33+
$array_sorted = $this->sortList($array_copy_to_sort);
34+
} while($array_copy[$last_element] < max($array_sorted));
35+
36+
for ($i = 0; $i < count($array_sorted); $i++) {
37+
$array_copy[$i] = $array_sorted[$i];
38+
}
39+
40+
for ($i = 0; $i < count($numbers_list); $i++) {
41+
if ($array_copy[$i] !== $numbers_list[$i]) {
42+
return FALSE;
43+
}
44+
}
45+
46+
return TRUE;
47+
}
48+
49+
}
50+
51+
?>
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
require('Bogobogosort.php');
4+
5+
class BogobogosortTest extends PHPUnit_Framework_TestCase {
6+
private $test_array = array(4, 17, 48, 2, 33);
7+
8+
public function testBogobogosort()
9+
{
10+
$bogobogosort = new BogoBogoSort();
11+
12+
$result = $bogobogosort->sortList($this->test_array);
13+
sort($this->test_array, SORT_NUMERIC);
14+
15+
$this->assertEquals($result, $this->test_array);
16+
}
17+
}

0 commit comments

Comments
 (0)