2014-04-09 27 views
0

我想測試不同的排序方法對於一個數組有多快。我在不同的文件中有排序方法,我試圖對數組排序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); 
} 
+2

循環之前把'Random'初始化。如果你想要不同的但可重複的數組值,只需要改變隨機種子:例如,Random r = new Random(1234 * nonce);',其中'nonce'是你必須設置的一次性值。對於更多不可預測的值,可以使用某種時間函數或其他「隨機性」來構建種子。 –

+1

對於這個特定的應用程序,每次使用相同的種子可能是有益的,因此您真正將排序時間與相同的數組進行比較。但是像@PaulLambert所說的,你需要在你的for循環之外移動「Random r = new Random(1234)」。 – dharms

回答

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

如果你把隨機數r =新的隨機(1234);在循環中,您每次都會初始化r。

相關問題