Merge sort algorithm has a worst-case performance of O(n log n) - that's a good performance of comparison-based sorting algorithm, moreover this algorithm is easy to understand, remember and repeat after while.
For implementation I'm going to use mergeSort method with the following signature:
<T extends Comparable<T>> void mergeSort(T[] arrayToSort, T[]resArray)
arrayToSort - array to be sorted
resArray - empty array with the same length as arrayToSort which will have all arrayToSort's items in a sorted order
In step one of merge sort we need to copy the content of arrayToSort into resArray and specify array's start and end indicies.
Now it's time to split an array in a central element and get two subarrays
int mid = lo + (hi - lo) / 2; // this is a central element index of array
1-st subarray elements will be from lo to mid indicies
2-nd subarray elements will be from mid + 1 to hi indicies
The following function can break up into subarrays recursively:
For implementation I'm going to use mergeSort method with the following signature:
<T extends Comparable<T>> void mergeSort(T[] arrayToSort, T[]resArray)
arrayToSort - array to be sorted
resArray - empty array with the same length as arrayToSort which will have all arrayToSort's items in a sorted order
In step one of merge sort we need to copy the content of arrayToSort into resArray and specify array's start and end indicies.
int lo = 0; int hi = arrayToSort.length - 1; for (int iter = 0; iter < arrayToSort.length; ++iter) { resArray[iter] = arrayToSort[iter]; }
Now it's time to split an array in a central element and get two subarrays
int mid = lo + (hi - lo) / 2; // this is a central element index of array
1-st subarray elements will be from lo to mid indicies
2-nd subarray elements will be from mid + 1 to hi indicies
The following function can break up into subarrays recursively:
<T extends Comparable<T>> void sortMerge(T[] arrayToSort, T[] resArray, int lo, int hi) { if (lo >= hi) return; int mid = lo + (hi - lo) / 2; sortMerge(arrayToSort, resArray, lo, mid); sortMerge(arrayToSort, resArray, mid + 1, hi); //merge(arrayToSort, resArray, lo, mid, hi); }


