JAVA method of randomly shuffling array order
- 2020-04-01 03:33:43
- OfStack
This article illustrates a JAVA method for randomly shuffling arrays. Share with you for your reference. The specific implementation method is as follows:
import java.util.Random;
public class RandomSort {
private Random random = new Random();
//Array size & NBSP; < br / >
private static final int SIZE = 10;
//Array & PI to be reordered; < br / >
private int[] positions = new int[SIZE];
public RandomSort() {
for(int index=0; index<SIZE; index++) {
//Initializes the array with the index as the element value & NBSP; < br / >
positions[index] = index;
}
//Print out the value of the array sequentially & NBSP; < br / >
printPositions();
}
//Reorder < br / >
public void changePosition() {
for(int index=SIZE-1; index>=0; index--) {
//You take a random value from 0 to index, and you swap & PI with the element at index; < br / >
exchange(random.nextInt(index+1), index);
}
printPositions();
}
//Swap places & NBSP; < br / >
private void exchange(int p1, int p2) {
int temp = positions[p1];
positions[p1] = positions[p2];
positions[p2] = temp; //A better place & NBSP; < br / >
}
//Print the value of the array & NBSP; < br / >
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 has been helpful to your Java programming.