Shuffle an array or a portion of an array - Java Collection Framework

Java examples for Collection Framework:Array Shuffle

Description

Shuffle an array or a portion of an array

Demo Code


//package com.java2s;
import java.util.Random;

public class Main {
    /**/*www .  j a  va  2 s .  c  om*/
     * Shuffle an array or a portion of an array
     *
     * @param array  The array to be shuffled
     * @param length The last index of the portion of the array to be shuffled
     */
    public static void shuffleArray(int[] array, int length) {
        int index, temp;
        Random random = new Random();
        for (int i = length - 1; i > 0; i--) {
            index = random.nextInt(i + 1);
            temp = array[index];
            array[index] = array[i];
            array[i] = temp;
        }
    }
}

Related Tutorials