Last active
August 29, 2015 14:01
-
-
Save albertofem/f418817ff2944977b414 to your computer and use it in GitHub Desktop.
Bogo sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// usage: php bogosort.php 1,2,3,4,5 | |
$items = explode(",", $argv[1]); | |
shuffle($items); | |
$shuffled = 0; | |
$ordered = bogoSort($items); | |
echo "Ordering took: " . $shuffled . " shuffles\n"; | |
function bogoSort(Array $items) | |
{ | |
global $shuffled; | |
while(!isInOrder($items)) | |
{ | |
echo "Shuffling!\n"; | |
$shuffled++; | |
shuffle($items); | |
} | |
return $items; | |
} | |
function isInOrder(Array $items) | |
{ | |
for ($i=1; $i<count($items); $i++) | |
if ($items[$i] < $items[$i-1]) | |
return false; | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment