Merge Sort is a Divide and Conquer algorithm. It divides input array in two halves, calls itself for the two halves and then merges the two sorted halves.
The merge() function is used for merging two halves. The merge(arr, l, m, r) is key process that assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
例子:
解决方案:
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r) The complete merge sort process for an example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively divided in two halves till the size becomes 1. Once the size becomes 1, the merge processes comes into action and starts merging arrays back till the complete array is merged.
具体分析:
- Time Complexity: Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation. T(n) = 2T(n/2) + Θ(n) The above recurrence can be solved either using Recurrence Tree method or Master method. Time complexity of Merge Sort is Θ(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and take linear time to merge two halves.
- Auxiliary Space: O(n)
- Algorithmic Paradigm: Divide and Conquer
- Sorting In Place: No in a typical implementation
- Stable: Yes
代码:
public class MergeSort {
public static void sort(int[] array){
int n = array.length;
mergeSort(array, 0, n - 1);
}
private static void mergeSort(int[] array, int l, int h){
if(l < h) {
int mid = l + ((h - l) / 2);
mergeSort(array, l, mid);
mergeSort(array, mid + 1, h);
merge(array, l, mid, h);
}
}
private static void merge(int[] array, int l, int mid, int h){
int[] auxiliary = new int[h-l+1];
int j = l, k = mid + 1, p = 0;
while(j <= mid && k <= h){
if(array[j]<=array[k]){
auxiliary[p++] = array[j++];
}else{
auxiliary[p++] = array[k++];
}
}
if(j <= mid){
for (int i = j; i <= mid; i++) {
auxiliary[p++] = array[i];
}
}
if(k <= h){
for (int i = k; i <= h; i++) {
auxiliary[p++] = array[i];
}
}
for (int i = l; i <= h; i++) {
array[i] = auxiliary[i - l];
}
}
public static void main(String[] args) {
int arr[] = {12, 11, 13, 5, 6, 7, 90};
MergeSort ms = new MergeSort();
ms.sort(arr);
System.out.println("Sorted array: ");
for (int i : arr){
System.out.print(i + " ");
}
}
}