网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文
当前位置:书香门第 > 计算机 > java语言

Java中shuffle算法的使用

栏目: java语言 / 发布于: / 人气:6.37K

导语:shuffle算法(洗牌算法)就是将顺序打乱,一个典型的应该就是音乐播放器随机播放,下面是Java中 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());