I made a mergesort which mergesorts an array in 3 parts instead of two in order to sort it and I wrote some code to test my mergesort if it works properly. Here is the code for the testing:
while (true){
Random rand = new Random();
int[] randArray = new int[rand.nextInt(2000)];
for (int i = 0; i < randArray.length; i++) {
randArray[i] = rand.nextInt();
}
int[] temporary = new int[randArray.length];
System.arraycopy(randArray, 0, temporary, 0, randArray.length);
mergesort(randArray);
Arrays.sort(temporary);
if (Arrays.equals(randArray, temporary)){
System.out.println("YES");
} else {
break;
}
}
}
What I’m doing is everytime create an array of up to 2000 integers and fill the array with random integers, then store that array in the temporary array, after that use my mergesort in the original array and use the Arrays.sort() method for the temporary array, then if the two arrays are equal print YES or else break from the while loop.
By now it hasn’t broken from the while loop and indicating that my algorithm is correct so I am asking if I did right here and wrote the testing code correctly.
EDIT: It is printing YES constantly without breaking from the loop so I believe it is working but I am asking so I can be sure
Your test code seems good to me, and that means your algorithm is mostly good as well. On the other hand, please don’t get me wrong, but this kind of testing can be considered only a quick and dirty check. If you want to do proper testing, you should test the following:
You should also consider using an automated test framework like JUnit.
And finally, using random input in a test is not a good practice, as the result of the tests can change from run to run.