I have to measure the time it takes quick-sort and merge-sort to sort out integers in a file with random numbers.
I read online that for a large amount of data merge-sort is supposed to be faster than quick-sort but my measurements say the opposite, merge-sort takes almost twice the time that quick-sort takes.
Is my implementation of these algorithms the problem?
Results of the measurements:
Quick-Sort:
- 5 milion int - 715,194,000 ns
- 10 milion int - 1,383,187,400 ns
- 50 milion int - 6,819,586,800 ns
- 100 milion int - 14,159,986,000 ns
- 150 milion int - 22,431,202,200 ns
Merge-Sort:
5 milion int - 1,644,349,000 ns
10 milion int - 2,186,410,800 ns
50 milion int - 14,427,917,500 ns
100 milion int - 26,487,337,400 ns
150 milion int - 42,229,109,700 ns
//Quick Sort Implementation public static void quickSort(int[] a, int start, int end){ if(end - start < 2){ return; } int pivtIndex = partition(a, start, end); quickSort(a, start, pivtIndex); quickSort(a, pivtIndex + 1, end); } public static int partition(int[] a, int start, int end){ int pivot = a[start]; int i = start; int j = end; while(i < j){ while(i < j && a[--j] >= pivot); if(i < j){ a[i] = a[j]; } while(i < j && a[++i] <= pivot); if(i < j){ a[j] = a[i]; } } a[j] = pivot; return j; } //Merge Sort Implementation public static void mergeSort(int[] input, int start, int end){ if(end - start < 2){ return; } int mid = (start + end)/2; mergeSort(input, start, mid); mergeSort(input, mid, end); merge(input, start, mid, end); } public static void merge(int[] input, int start, int mid, int end){ if(input[mid-1] <= input[mid]){ return; } int i = start, j = mid, tempIndex = 0; int[] temp = new int[end - start]; while(i < mid && j < end){ temp[tempIndex++] = input[i] <= input[j] ? input[i++] : input[j++]; } System.arraycopy(input, i, input, start + tempIndex, mid - i); System.arraycopy(temp, 0, input, start, tempIndex); }