I am trying to write a method comparing the run times of four different sorting algorithms (mergesort, quicksort, heapsort, insertionsort). I am trying to time each algorithm with each iteration of the for loop, which increases the array size of a randomly generated array each loop. The code that I have works but takes way too much time. At the end of the loop, I am calculating the average time each sorting algorithm took over the arrays from size 1 to 100.
Note: generateArray(num) just creates an array filled with random integers of size num.
I'm not such a great coder, what would be a way to implement it better?
Here's the code snippet:
static void testArrays() {
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long insertionCount=0, mergeCount=0,
quickCount=0, heapCount = 0;
for (int i=1; i<100; i++) {
long[] A = generateArray(i);
long[] copy1 = A.clone();
long[] copy2 = A.clone();
long[] copy3 = A.clone();
long startTime1 = bean.getCurrentThreadCpuTime();
insertionSort(A);
long endTime1 = bean.getCurrentThreadCpuTime();
long duration = endTime1 - startTime1;
insertionCount = insertionCount + duration;
long startTime2 = bean.getCurrentThreadCpuTime();
mergeSort(copy1);
long endTime2 = bean.getCurrentThreadCpuTime();
long mergeDuration = endTime2 - startTime2;
mergeCount = mergeCount + mergeDuration;
long startTime3 = bean.getCurrentThreadCpuTime();
heapSort(copy2);
long endTime3 = bean.getCurrentThreadCpuTime();
long heapDuration = endTime3 - startTime3;
heapCount = heapCount + heapDuration;
long startTime4 = bean.getCurrentThreadCpuTime();
quickSort(copy3);
long endTime4 = bean.getCurrentThreadCpuTime();
long quickDuration = endTime4 - startTime4;
quickCount = quickCount + quickDuration;
}
long averageIS = insertionCount/10000;
long averageMS = mergeCount/10000;
long averageHS = heapCount/10000;
long averageQS = quickCount/10000;
System.out.println("Insertion Sort Avg: " + averageIS);
System.out.println("MergeSort Avg: " + averageMS);
System.out.println("HeapSort Avg: " + averageHS);
System.out.println("QuickSort Avg: " + averageQS);
}