快速搜索
主页 > 软件开发 > JAVA开发 >

JAVA随机打乱数组顺序的方法

时间:2014-11-27 02:38来源:网络整理 作者:网络 点击:
分享到:
这篇文章主要介绍了JAVA随机打乱数组顺序的方法,包含了随机数的应用及数组的排序等操作,是Java操作数组的典型应用,需要的朋友可以参考下

本文实例讲述了JAVA随机打乱数组顺序的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
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
??????????? //初始化数组,以下标为元素值???
??????????? 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
??????????? System.out.print(positions[index]+" ");????????????
??????? }???
??????? System.out.println();???
??? }???
???
??? public static void main(String[] args) {???
??????? RandomSort rs = new RandomSort();???
??????? rs.changePosition();???
??????? rs.changePosition();???
??????? rs.changePosition();???
??? }???
}

希望本文所述对大家的Java程序设计有所帮助。

精彩图集

赞助商链接