當前位置:才華齋>計算機>java語言>

Java中shuffle演算法的使用

java語言 閱讀(5.66K)

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