Bogo Sort

Bogo sort, also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort, is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting, but may be used for educational purposes, to contrast it with other more realistic algorithms.



									function IsSorted(&$data)
{
	$count = count($data);

	while (--$count >= 1)
		if ($data[$count] < $data[$count - 1]) return false;

	return true;
}

function ShuffleData(&$data)
{
	$count = count($data);
	
	for ($i = 0; $i < $count; ++$i)
	{
		$rnd = rand() % $count;
		$temp = $data[$i];
		$data[$i] = $data[$rnd];
		$data[$rnd] = $temp;
	}
}

function BogoSort(&$data)
{
	while (!IsSorted($data))
		ShuffleData($data);
}
								


Example

									$data = array(-1, 25, -58964, 8547, -119, 0, 78596);
BogoSort($data);
								


Output

									-58964
-119
-1
0
25
8547
78596