EN
Java - random sort array
9
points
In this short article, we would like to show how in Java, sort array to archive random order.
The below example implements Fisher–Yates shuffle algorithm:
package com.example;
import java.util.Arrays;
import java.util.Random;
public class Program
{
public static void main(String[] args) throws Exception {
int[] array = {
1, 2, 3, 4, 5
};
Random random = new Random();
for (int i = array.length - 1; i > 0; --i) {
int j = random.nextInt(i);
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
System.out.println(Arrays.toString(array));
}
}
Example output:
[4, 1, 5, 3, 2]
Reusable code example
This section contains class prepared co copy as util.
Alternatively, you can use ArrayUtils.shuffle()
method provided by Apache Lang library (installation instruction here).
Program.java
file:
package com.example;
import java.util.Arrays;
public class Program {
public static void main(String[] args) throws Exception {
Integer[] array = {
1, 2, 3, 4, 5
};
ArrayUtils.shuffle(array);
System.out.println(Arrays.toString(array));
}
}
ArrayUtils.java
file:
package com.example;
import java.util.Random;
public class ArrayUtils {
public static <T> void shuffle(T[] array) {
Random random = new Random();
for (int i = array.length - 1; i > 0; --i) {
int j = random.nextInt(i);
T tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
}
}