Home > Java > javaTutorial > body text

How to randomly shuffle the order of an array in java

WBOY
Release: 2023-04-26 10:52:16
forward
1963 people have browsed it

1. Process

(1) Array size and array to be reordered;

(2) Initialize the array, with the subscript as the element value;

(3) Print out the values ​​of the array in sequence and reorder;

(4) Randomly pick a value from 0 to index, exchange it with the element at index, and adjust the position.

2、Example

import java.util.Random;  
  
public class RandomSort {  
    private Random random = new Random();  
    //数组大小  
    private static final int SIZE = 10;  
    //要重排序的数组  
    private int[] positions = new int[SIZE];  
      
    public RandomSort() {  
        for(int index=0; index<SIZE; index++) {  
            //初始化数组,以下标为元素值  
            positions[index] = index;  
        }  
        //顺序打印出数组的值  
        printPositions();
    }  
      
    //重排序  
    public void changePosition() {  
        for(int index=SIZE-1; index>=0; index--) {  
            //从0到index处之间随机取一个值,跟index处的元素交换  
            exchange(random.nextInt(index+1), index);  
        }  
        printPositions();  
    }  
      
    //交换位置  
    private void exchange(int p1, int p2) {  
        int temp = positions[p1];  
        positions[p1] = positions[p2];  
        positions[p2] = temp;  //更好位置
    }  
      
    //打印数组的值  
    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();  
    }  
}
Copy after login

The above is the detailed content of How to randomly shuffle the order of an array in java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template