Java Array random shuffle

Introduction

To randomly reorder the elements in an array:

for each element array[i], randomly generate an index j and swap array[i] with array[j]

import java.util.Arrays;

public class Main {
  public static void main(String[] args) {
    int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    System.out.println(Arrays.toString(array));
    for (int i = array.length - 1; i > 0; i--) {
      int j = (int) (Math.random() * (i + 1));
      int temp = array[i];
      array[i] = array[j];// w ww  .  ja  v a 2 s.com
      array[j] = temp;
    }

    System.out.println(Arrays.toString(array));
  }
}



PreviousNext

Related