超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<rsortsizeof>
Last updated: Fri, 22 Jun 2007

shuffle

(PHP 3>= 3.0.8, PHP 4 , PHP 5)

shuffle -- 将数组打乱

说明

void shuffle ( array array)

本函数打乱(随机排列单元的顺序)一个数组。必须用 srand() 播下本函数的随机数发生器种子。

例子 1. shuffle() 例子

<?php
$numbers
= range (1,20);
srand ((float)microtime()*1000000);
shuffle ($numbers);
while (list (,
$number) = each ($numbers)) {
   echo
"$number ";
}
?>

注: 在 PHP 4.2.0 中,无需用函数 srand()mt_srand()来搜寻随机数生成器,它将被自动完成。

参见 arsort()asort()ksort()rsort()sort()usort()




add a note add a note User Contributed Notes
shuffle
Justin Knoll
14-Nov-2003 04:57
Here's an implementation of a canonical shuffling algorithm.

Its O(n), not O(n^2). The implementation of Fisher-Yates below uses array splicing inside a for loop over the array, making it O(n^2).

It creates a uniform distribution of permutations - the definition of a shuffle. I'm not sure that all of the ad hoc algorithms below do this - they might create shuffles that look random on casual inspection, but aren't.

Many implementations of Fisher-Yates check to make sure that $i != $j before swapping. I figure that for large lists, that check incurs more cost than just swapping every time.

<?php
/**
* Shuffles an array using the Fisher-Yates shuffle.
*
* D. E. Knuth: The Art of Computer Programming, Volume 2,
* Third edition. Section 3.4.2, Algorithm P, pp 145. Reading:
* Addison-Wesley, 1997. ISBN: 0-201-89684-2.
*
* R. A. Fisher and F. Yates: Statistical Tables. London, 1938.
* Example 12.
*
* @author Justin Knoll
* @param array The array to be sorted - passed by reference.
* @return The shuffled array.
*/
function fisherYatesShuffle(&$array)
{
for ($i = count($array); --$i; $i > 0)
{
$j = @mt_rand(0, $i+1);
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
?>

<rsortsizeof>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22