实现Fisher Yates算法

时间:2016-10-10 14:56:50

标签: java

我在java中有一个方法,可以随机化一个数组中的整数。但是它需要太长时间,我试图找到更快的方法来做到这一点,我认为fisher Yates算法是解决方案,但我不知道如何用我的代码实现这一点。

protected void randomise() {
    int[] copy = new int[getArray().length];
    // used to indicate if elements have been used
    boolean[] used = new boolean[getArray().length];
    Arrays.fill(used,false);
    for (int index = 0; index < getArray().length; index++) {
        int randomIndex;
        do {
            randomIndex = getRandomIndex();
        } while (used[randomIndex]);
        copy[index] = getArray()[randomIndex];
        used[randomIndex] = true;
    }
    for (int index = 0; index < getArray().length; index++) {
        getArray()[index] = copy[index];
    }
}
/*
 * A method which prints out the list of nubers
 */

public static void main(String[] args) {
    RandomListing count = new SimpleRandomListing(1000000);
    System.out.println(Arrays.toString(count.getArray()));
}

2 个答案:

答案 0 :(得分:0)

N = array.length;
for i in [0, 1, 2, ..., N - 1]:
  random_index = random(i, N - 1);
  swap(array[i], array[random_index]);

答案 1 :(得分:0)

这是Fisher-Yates的实施

public static <T> void fyShuffle(T[] elem, Random rng){
    int index = 0;
    T temp = null;

    //Fisher–Yates shuffle the 'elem' array
    for (int i = elem.length - 1; i > 0; i--) {
        index = rng.nextInt( i + 1 );
        temp = elem[index];
        elem[index] = elem[i];
        elem[i] = temp;
    }
}

您还可以使用Collections.shuffle( collection )来收集一个集合(例如List<>