Tuesday, September 17, 2013

Shuffle an Array in Java with Easy or Fast way


Objects are a powerful software engineering construct, and Java uses them extensively. While developing Android applications you need fast way of doing something. For example:
Often u need randomized Array which u will save state of stage or something.
In that case how you change order of Array randomly???


There are 2 famous way for this:


Collections.shuffle(Arrays.asList(arr));
This way is easy to use
And the second way is FAST

for (int i=0; i < arr.length; i++) {
 int randomPosition = randomizer.nextInt(arr.length);
 String temp = arr[i];
 arr[i] = arr[randomPosition];
 arr[randomPosition] = temp;
}
The full example source code is following:
package com.example;

import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

public class Shuffle {
 
 public static void main(String[] args) {
  String[] arr = new String[999999];
  Random randomizer = new Random();
  for (int i = 0; i < arr.length; i++) {
   arr[i] = "test"+i;
  }
  
  long startTime = System.currentTimeMillis();
  suffleEasy(arr);
  System.out.println("suffleEasy=>"+(System.currentTimeMillis() - startTime));
  
  startTime = System.currentTimeMillis();
  suffleFast(arr, randomizer);
  System.out.println("suffleFast=>"+(System.currentTimeMillis() - startTime));
 }
 
 
 private static void suffleEasy(String[] arr){
  Collections.shuffle(Arrays.asList(arr));
 }
 
 
 private static void suffleFast(String[] arr, Random randomizer){
  for (int i=0; i < arr.length; i++) {
   int randomPosition = randomizer.nextInt(arr.length);
   String temp = arr[i];
   arr[i] = arr[randomPosition];
   arr[randomPosition] = temp;
  }
 }

}
While running this example in my case the output was:
suffleEasy=>84
suffleFast=>33

No comments:

Post a Comment