Java中shuffle算法的使用

來源:文萃谷 4.84K

導語: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());

熱門標籤