import java.util.Random;
import java.util.Scanner;
public class ShufflingExample{
final static int NUM_REPETITIONS = 5;
Swaps two items, basedh on their indices.
@param a
@param i1
@param i2
public static void swap(int[] a, int i1, int i2){
int temp = a[i1];
a[i1] = a[i2];
a[i2] = temp;
}
Finds the largest item in an array.
@param a
@param n
@return
public static int indexOfLargest(int[] a, int n){
int indexSoFar = 0;
for( int currentIndex = 1; currentIndex < n; ++currentIndex){
if( a[currentIndex] > a[indexSoFar] ){
indexSoFar = currentIndex;
}
}
return indexSoFar;
}
Sorts the items in the keyArray into ascending order and performs the same
rearrangements on otherArray.
@param keyArray
@param otherArray
@param n
public static void sort2Arrays(int[] keyArray, int[] otherArray, int n){
for( int last = n-1; last >= 1; --last){
int largest = indexOfLargest(keyArray, last+1);
swap( keyArray, largest, last);
swap( otherArray, largest, last);
}
}
public static void shuffle1(int[] array, Random rand){
int[] randomValues = new int[ array.length ];
for( int i = 0; i < array.length; i++){
randomValues[i] = rand.nextInt();
}
sort2Arrays( randomValues, array, array.length);
}
public static void shuffle2(int[] array, Random rand){
int randIndex = -1;
for( int i = 0; i < array.length; i++){
randIndex = Math.abs(rand.nextInt()) % array.length;
swap( array, i, randIndex );
}
}
public static void main( String[] args ){
long begin, end;
Random rand = new Random();
Scanner stdinScanner = new Scanner( System.in );
int maxN = -1;
while( maxN <= 0 ){
try{
System.out.print("Enter the maximum value of N: ");
maxN = stdinScanner.nextInt();
}catch(Exception e){
System.err.println("Error retrieving a whole number from input");
stdinScanner.next();
}
}
System.err.println( "\tShuffle1\tShuffle2" );
System.err.println( "n\t(ms)\t(ms)" );
for(int n = 10; n <= maxN; n *= 10){
System.err.print( n );
int[] array = new int[n];
int timeElapsed = 0;
for( int j = 0; j < NUM_REPETITIONS; j++){
for( int i = 0; i < n; i++){
array[i] = i;
}
begin = System.currentTimeMillis();
shuffle1( array, rand);
end = System.currentTimeMillis();
timeElapsed += end - begin;
}
System.err.print( "\t" + timeElapsed );
timeElapsed = 0;
for( int j = 0; j < NUM_REPETITIONS; j++){
for( int i = 0; i < n; i++){
array[i] = i;
}
begin = System.currentTimeMillis();
shuffle2( array, rand);
end = System.currentTimeMillis();
timeElapsed += end - begin;
}
System.err.println( "\t" + timeElapsed );
}
}
}