The example in this article describes the method of randomly shuffling the order of arrays in JAVA. Share it with everyone for your reference. The specific implementation method is as follows:
Copy the code as follows: import java.util.Random;
public class RandomSort {
private Random random = new Random();
//array size
private static final int SIZE = 10;
//Array to be reordered
private int[] positions = new int[SIZE];
public RandomSort() {
for(int index=0; index<SIZE; index++) {
//Initialize the array, with the subscript as the element value
positions[index] = index;
}
//Print out the values of the array sequentially
printPositions();
}
//reorder
public void changePosition() {
for(int index=SIZE-1; index>=0; index--) {
// Randomly pick a value from 0 to index and exchange it with the element at index
exchange(random.nextInt(index+1), index);
}
printPositions();
}
//Swap positions
private void exchange(int p1, int p2) {
int temp = positions[p1];
positions[p1] = positions[p2];
positions[p2] = temp; //Better position
}
//Print the value of the array
private void printPositions() {
for(int index=0; index<SIZE; index++) {
System.out.print(positions[index]+" ");
}
System.out.println();
}
public static void main(String[] args) {
RandomSort rs = new RandomSort();
rs.changePosition();
rs.changePosition();
rs.changePosition();
}
}
I hope this article will be helpful to everyone’s Java programming.