Java中shuffle算法的使用
- java语言
- 关注:3.93K次
导语:shuffle算法(洗牌算法)就是将顺序打乱,一个典型的应该就是音乐播放器随机播放,下面是Java中 shuffle 算法的使用,一起来学习下吧:
Fisher–Yates shuffle 基本思想(Knuth shuffle ):
To shuffle an array a of n elements (indices 0..n-1):
for i from n 1 downto 1 do
j ← random integer with 0 ≤ j ≤ i
exchange a[j] and a[i]
JDK源代码如下:
代码如下:
/**
* Moves every element of the List to a random new position in the list.
*
* @param list
* the List to shuffle
*
* @throws UnsupportedOperationException
* when replacing an element in the List is not supported
*/
public static void shuffle(List list) {
shuffle(list, new Random());
- 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/ej65w9.html