【java】数组随机乱序排列

每次从已知数组随机一个数,然后将数组的最后一个值 赋值给前面随机到的数的位置上,然后将长度-1,再从原数组下标-1的数组中随机。 运算次数就是数组长度
//-----------------------------------------------
public int [] m3(int [] arr) {
int [] arr2 =new int[arr.length];
int count = arr.length;
int cbRandCount = 0;// 索引
int cbPosition = 0;// 位置
int k =0;
do {
runCount++;
Random rand = new Random();
int r = count - cbRandCount;
cbPosition = rand.nextInt( r );
arr2[k++] = arr[cbPosition];
cbRandCount++;
arr[cbPosition] = arr[r - 1];// 将最后一位数值赋值给已经被使用的cbPosition
} while (cbRandCount < count);
System.out.println("m3运算次数 = "+runCount);
return arr2;
}

引用自:https://blog.csdn.net/gywtzh0889/article/details/52886618

你可能感兴趣的:(实验)