I want to implement a benchmark where the Method MergeSort and it’s performance is measured. I have tried to fill the array that is to be mergesorted with random numbers but when the code is run the array prints the same random number 10 times. Why is this?
PS. I can’t post the entire program I have written. Stackoverflow is saying it’s too much code.
public static void main(String[] args) { int arraySize = 10; int[] a = new int[arraySize]; int k = 1000; int m = 1000; Random rnd = new Random(); for (int j = 0; j < k; j++) { // fill the arraySize array with random numbers for (int i = 0; i < 10*m; i++) { Arrays.fill(a, rnd.nextInt()); } } long startTime = System.nanoTime(); // array with predefined numbers and size //int[] a = { 11, 30, 24, 7, 31, 16, 39, 41 }; int n = a.length; MergeSort m1 = new MergeSort(); System.out.println("nBefore sorting array elements are: "); m1.printArray(a, n); m1.mergeSort(a, 0, n - 1); long endTime = System.nanoTime(); long timeElapsed = endTime - startTime; System.out.println("nnExecution time in nanoseconds: " + timeElapsed); System.out.println("Execution time in milliseconds: " + timeElapsed / 1000000); System.out.println("nAfter sorting array elements are:"); m1.printArray(a, n); } }
Advertisement
Answer
for (int i = 0; i < 10*m; i++){ Arrays.fill(a, rnd.nextInt()); }
This loop fills the array with one number 10*m times. That’s why you have the same number for the entire array.
Solution:
int arraySize = 10; int[] a = new int[arraySize]; for (int i = 0; i < arraySize; i++) a[i] = rnd.nextInt(1000); System.out.println(Arrays.toString(a));