logo

Algorithms - Shuffle

To shuffule an array: use a moving point, at every step, randomly pick a position in the remaining unshuffled section, swap the current value and the selected value, move the pointer to the next position.

Example Java code:

public static void shuffle(int[] a) {
    for (int i = 0; i < a.length; i++){
        int k = (int) (Math.random() * (a.length - i)) + i;
        int tmp = a[k];
        a[k] = a[i];
        a[i] = tmp;
    }
}