开发者

Efficient array elements un-ordering in Java

开发者 https://www.devze.com 2023-01-20 12:28 出处:网络
I just wanted to know what is the best way to un-order th开发者_Go百科e elements in an ordered array in Java,

I just wanted to know what is the best way to un-order th开发者_Go百科e elements in an ordered array in Java, Thanks


I think you want Collections.shuffle(List)? If not that, you will need to give us more details about what you're trying to do.


You want to shuffle that array using a good algorithm.

I would trust Collections#shuffle to implement this properly. If you need it to work on the array directly, implement the algorithm in your own helper method.


I don't know much Java, so there may be better way, but this'll do the trick nicely.

Fisher-Yates shuffle from Wikipedia:

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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号