Java array shuffle

Description

Java array shuffle


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

public class Main {
  public static int[] shuffle(int[] numbers) {
    for (int i = 0; i < numbers.length; i++) {
      int index = new Random().nextInt(i + 1);
      int swap = numbers[index];
      numbers[index] = numbers[i];//from  ww w  .java2s . c  o  m
      numbers[i] = swap;
    }
    return numbers;
  }
  public static void main(String[] args) {
    int[] i = shuffle(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 });
    System.out.print(Arrays.toString(i));
  }
}
import java.util.Arrays;
import java.util.Random;

public class Main {
  public static void main(String args[]) {
    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
    shuffleArray(array);//from   w  w  w  .  j  ava  2s . c  o m
    System.out.println(Arrays.toString(array));
  }

  static void shuffleArray(int[] ar) {
    Random rnd = new Random();
    for (int i = ar.length - 1; i > 0; i--) {
      int index = rnd.nextInt(i + 1);
      // Simple swap
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }
}



PreviousNext

Related