note 41593 added to function.shuffle
| From: | JustinKnoll at rn2 dot php dot net | Date: | Thu, 15 Apr 2004 21:24:29 +0000 |
| Subject: | note 41593 added to function.shuffle | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-68179@lists.php.net to get a copy of this message | ||
This code is very appealing in its simplicity and speed, but it's not a random shuffle:
<?php
function randomcmp($a, $b)
{
return mt_rand(-1, 1);
}
function swapshuffle(&$array)
{
srand((double) microtime() * 10000000);
uksort($array, "randomcmp");
}
?>
This is because uksort calls the C function zend_qsort and this quicksorts the array using the
provided comparision function. The pairs of indices selected are biased by the nature of the
quicksort algorithm.
One effect is that an element in the middle of the array is heavily biased toward being
"shuffled" to the middle. Elements on the edges are biased towards the edges; they're
likely to switch edges, but unlikely to end up in the middle.
----
Manual Page -- http://www.php.net/manual/en/function.shuffle.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41593
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41593&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41593&report=yes
Search -- http://master.php.net/manage/user-notes.php