Java 使用不同的选择方法对随机数组进行多次排序
我试图测试一个数组的不同排序方法的速度。我在另一个文件中使用了排序方法,我试图对数组进行10次排序并找到时间,但每次都很难得到一个新的随机数数组 以下是我目前的代码:Java 使用不同的选择方法对随机数组进行多次排序,java,arrays,sorting,Java,Arrays,Sorting,我试图测试一个数组的不同排序方法的速度。我在另一个文件中使用了排序方法,我试图对数组进行10次排序并找到时间,但每次都很难得到一个新的随机数数组 以下是我目前的代码: public static int[] makeArray(int x) { int[] a = new int [x]; for( int i = 0; i < x; i ++) { Random r = new Random(1234); a[i] = r.nextInt(
public static int[] makeArray(int x) {
int[] a = new int [x];
for( int i = 0; i < x; i ++) {
Random r = new Random(1234);
a[i] = r.nextInt();
}
System.out.println(Arrays.toString(a));
return a;
}
public static void main(String[] args) {
int x = 100;
int [] arr = makeArray(x);
for(int i = 0; i <x; i++) {
int[] copy = new int [x];
copy[i] = arr[i];
}
long t = System.nanoTime();
Sorts.SelectionSort(arr);
long y = System.nanoTime();
long totalTime = y-t;
System.out.println("time = " + totalTime);
long z = System.nanoTime();
Sorts.SelectionSort(copy);
long w = System.nanoTime();
System.out.println("time = " + w-z);
}
publicstaticint[]makeArray(intx){
int[]a=新的int[x];
对于(int i=0;i
public static int[] makeArray(int x) {
int[] a = new int [x];
Random r = new Random(1234);
for( int i = 0; i < x; i ++) {
a[i] = r.nextInt();
}
System.out.println(Arrays.toString(a));
return a;
}
public static void main(String[] args) {
int x = 100;
int [] arr = makeArray(x);
for(int i = 0; i <x; i++) {
int[] copy = new int [x];
copy[i] = arr[i];
}
long t = System.nanoTime();
Sorts.SelectionSort(arr);
long y = System.nanoTime();
long totalTime = y-t;
System.out.println("time = " + totalTime);
long z = System.nanoTime();
Sorts.SelectionSort(copy);
long w = System.nanoTime();
System.out.println("time = " + w-z);
}
publicstaticint[]makeArray(intx){
int[]a=新的int[x];
随机r=新随机(1234);
对于(int i=0;i 对于(int i=0;我将Random
初始化放在循环之前。如果需要不同但可重复的数组值,只需更改随机种子:例如,Random r=new Random(1234*nonce);
,其中nonce
是您必须设置的某个一次性值。对于更不可预测的值,请使用某种时间函数或其他“随机性”来源构建种子。对于这个特定的应用程序,每次使用相同的种子可能是有益的,这样您就可以真正比较同一数组的排序时间。但正如@PaulLambert所说,您需要将Random r=new Random(1234);
移动到For循环之外。