Merge sort, is also based on the idea of divide and conquer, the array is divided continuously until the end of an element, and then 22 merge, because from the beginning of an element, so that each of the merged array is ordered, the merge only need a constant time to complete, so its time recursion is: T (n) = 2T (N/2) + O (n ), the previous item is a time complexity divided into two sub-arrays, and the latter is the time complexity of merging two sorted arrays is O (n),
Its running process, here on the Internet to find a diagram, it is clear that the process:
Here is a merge-sort demo of Java:
public static void MergeSort (int[] A, int start, int end) {
int[] sorted = new Int[a.length];
if (Start < end) {
int mid = (start + end)/2;
MergeSort (A,start,mid);
MergeSort (A,mid+1,end);
Merge (a,start,mid,end,sorted);
}
}
public static void merge (Int[] A, int. left, int mid, int right,int[] sorted) {
int i = left;
int k = left;
int j= mid+1;
while (I <= mid && J <= right) {
if (A[i] < a[j]) {
sorted[k++] = a[i++];
}else{
sorted[k++] = a[j++];
}
}
Copy the second part
while (I <= mid) {
sorted[k++] = a[i++];
}
while (J <= right) {
sorted[k++] = a[j++];
}
Copy the correct location
for (int q = left, q <= right; q++) {
A[Q] = Sorted[q];
}
}
public static void Main (string[] args) {
Int[] A = {1,4,5,32,3,44};
MergeSort (a,0,a.length-1);
for (int e:a) {
System.out.print (E + "");
}
}
Learning Merge Sort