zoukankan      html  css  js  c++  java
  • java 公平打乱数组顺序 重新排列

    01.import java.util.Random;    
    02.    
    03.public class RandomSort {    
    04.    private Random random = new Random();    
    05.    //数组大小    
    06.    private static final int SIZE = 10;    
    07.    //要重排序的数组    
    08.    private int[] positions = new int[SIZE];    
    09.        
    10.    public RandomSort() {    
    11.        for(int index=0; index<SIZE; index++) {    
    12.            //初始化数组,以下标为元素值    
    13.            positions[index] = index;    
    14.        }    
    15.        //顺序打印出数组的值    
    16.        printPositions();  
    17.    }    
    18.        
    19.    //重排序    
    20.    public void changePosition() {    
    21.        for(int index=SIZE-1; index>=0; index--) {    
    22.            //从0到index处之间随机取一个值,跟index处的元素交换    
    23.            exchange(random.nextInt(index+1), index);    
    24.        }    
    25.        printPositions();    
    26.    }    
    27.        
    28.    //交换位置    
    29.    private void exchange(int p1, int p2) {    
    30.        int temp = positions[p1];    
    31.        positions[p1] = positions[p2];    
    32.        positions[p2] = temp;  //更好位置  
    33.    }    
    34.        
    35.    //打印数组的值    
    36.    private void printPositions() {    
    37.        for(int index=0; index<SIZE; index++) {    
    38.            System.out.print(positions[index]+" ");             
    39.        }    
    40.        System.out.println();    
    41.    }    
    42.    
    43.    public static void main(String[] args) {    
    44.        RandomSort rs = new RandomSort();    
    45.        rs.changePosition();    
    46.        rs.changePosition();    
    47.        rs.changePosition();    
    48.    }    
    49.}    
  • 相关阅读:
    Docker 镜像
    为什么要用 Docker
    什么是 Docker
    python编码
    Python File(文件) 方法
    Python 日期和时间
    Python 字符串字典内置函数&方法
    Python 元组内置函数
    Epos消费管理系统使用发布订阅实现数据库SQL SERVER 2005同步复制
    Epos消费管理系统复制迁移SQL SERVER 2005数据库
  • 原文地址:https://www.cnblogs.com/fengshuzi/p/2997119.html
Copyright © 2011-2022 走看看