2010-10-14 31 views
1

我只是想知道什麼是對取消訂單的最好方式在Java中的有序數組中的元素, 感謝高效的數組元素未排序在Java中

+1

通過unorder,我認爲你的意思是洗牌? – spender 2010-10-14 00:58:26

+1

http://stackoverflow.com/questions/180979/using-collections-api-to-shuffle – 2010-10-14 00:59:48

回答

6

我想你想Collections.shuffle(List)?如果不是這樣,你需要給我們更多關於你想要做什麼的細節。

+0

你可以相當肯定Collections.shuffle()的混洗算法非常好。標準的JavaSE API經過了不可思議的測試。 (哇......不想聽起來像是賣話) – 2010-10-14 01:07:36

+0

那正是我在找的東西,謝謝你們! – 2010-10-15 11:39:55

1

我不太瞭解Java,因此可能會有更好的方法,但這會很好地實現。

Fisher-Yates shuffle維基百科:

static Random rng = new Random(); 
public static void shuffle(int[] array) { 
    // i is the number of items remaining to be shuffled. 
    for (int i = array.length; i > 1; i--) { 
     // Pick a random element to swap with the i-th element. 
     int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array) 
     // Swap array elements. 
     int tmp = array[j]; 
     array[j] = array[i-1]; 
     array[i-1] = tmp; 
    } 
} 
2

你想使用洗牌是a good algorithm陣列。

我會信任Collections#shuffle來正確實施。如果您需要它直接在陣列上工作,請使用您自己的幫助器方法實現該算法。