Randomly permute the Objects in an array. - Java XML

Java examples for XML:DOM

Description

Randomly permute the Objects in an array.

Demo Code


import java.util.*;
import java.math.*;

public class Main{
    static private Random value = new Random();
    /** Randomly permute the Objects in an array.
    @param A The array//from  www .  java  2  s  . co m
     */

    //int version
    //Randomly permute the values of array "A"
    static void permute(int[] A) {
        for (int i = A.length; i > 0; i--)
            // for each i
            swap(A, i - 1, DSutil.random(i)); //   swap A[i-1] with
    }
    static <E> void permute(E[] A) {
        for (int i = A.length; i > 0; i--)
            // for each i
            swap(A, i - 1, DSutil.random(i)); //   swap A[i-1] with
    }
    public static <E> void swap(E[] A, int p1, int p2) {
        E temp = A[p1];
        A[p1] = A[p2];
        A[p2] = temp;
    }
    public static void swap(int[] A, int p1, int p2) {
        int temp = A[p1];
        A[p1] = A[p2];
        A[p2] = temp;
    }
    static int random(int n) {
        return Math.abs(value.nextInt()) % n;
    }
}

Related Tutorials