使用不同的选择方法多次对随机数组进行排序

时间:2014-04-09 03:19:57

标签: 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();
    }
    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);
}

1 个答案:

答案 0 :(得分:0)

你必须这样做:

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);
}

如果你把Random r = new Random(1234);在循环中你每次都初始化r。