/**
* 把一个数组的顺序打乱,很常用的算法,比如洗牌。
* @author wWX154783
*/
public class Test_wzs9
{
private Random random = new Random();
// 数组大小
private static final int SIZE = 10;
// 要重排序的数组
private int[] positions = new int[SIZE];
public Test_wzs9()
{
for (int index = 0; index < SIZE; index++)
{
// 初始化数组,以下标为元素值
positions[index] = index;
}
// 顺序打印出数组的值
dwn();
}
// 重排序
public void changePosition()
{
for (int index = 0; index < 10; index++)
{
// 从0到index处之间随机取一个值,跟index处的元素交换
exchange(index, random.nextInt(index + 1));
}
dwn();
}
// 交换位置
private void exchange(int p1, int p2)
{
int temp = positions[p1];
positions[p1] = positions[p2];
positions[p2] = temp;
}
// 打印数组的值
private void dwn()
{
for (int index = 0; index < SIZE; index++)
{
System.out.print(positions[index] + " ");
}
System.out.println();
}
public static void main(String[] args)
{
Test_wzs9 rs = new Test_wzs9();
rs.changePosition();
rs.changePosition();
rs.changePosition();
}
}
打乱数组排序
最新推荐文章于 2024-01-19 01:00:00 发布