Merge sort
Recursively divides the existing sequences into two subsequences, so that the subsequences are ordered and the subsequences are merged
- The input sequence of length n is divided into two subsequences of length n/2;
- The two subsequences are sorted by merging;
- Merge two sorted subsequences into a final sorting sequence.
Java implementation merge sort
public class MergeSort { private static int[] aux;//Auxiliary array required for merging public static void mergeSort(int[] nums){ aux = new int[nums.length]; sort(nums,0,nums.length-1);//Start recursive sort } //Merge sort private static void sort(int[] nums,int left,int right){ if(right <= left)//Sort from left to right, make sure the right side is larger than the left return; int mid = (left + right) / 2;//Middle position sort(nums,left,mid);//Sort left half sort(nums,mid+1,right);//Sort right half merg(nums,left,mid,right);//Merging result } //Merge and sort in place private static void merg(int[] nums,int left,int mid,int right){ int i = left,j = mid + 1;//Start position of left and right half for(int k = left;k <= right;k++){//Copy nums[left...right] to aux[left...right] aux[k] = nums[k]; } for(int k = left;k <= right;k++){//Merge back to a[left...right] if(i > mid){//i larger than mid means the left half is used up, and only the right half has elements nums[k] = aux[j++]; }else if(j > right){//j larger than right means the right half is used up, and only the left half has elements nums[k] = aux[i++]; }else if(aux[j] < aux[i]){//Right element is smaller than left nums[k] = aux[j++];//The right element gives a[k] }else {//Otherwise, the right side is greater than or equal to the left side nums[k] = aux[i++];//The left element gives a[k] } } } }
summary
The worst, best and average running time of merge sorting is O(NlogN), but it needs extra storage space, which will be limited on some memory intensive machines. The merging algorithm is composed of two parts: segmentation and merging. For each part, if we use binary search, the time is O(NlogN), and at the last merging time is O(N), so the total time is O(NlogN). The spatial complexity is O(N).
The merge sorting is stable. Since there is no data exchange, when a=b, if a is in front of b at the beginning, it will still be in front of b after each merge, so the sorting algorithm is stable.