The merge sort is to divide the unsorted array into two arrays, and the divided array is only half the number of elements of the original array. Then continue dividing the two arrays on the partition, looping this operation until only one element in the divided array stops dividing, and then merges the sorting of the finished array. Merges the two already divided arrays into an ordered array until it is finally merged into an array containing all the elements, and the merge sort operation completes. The following is a graphical demonstration of the merge sort process.
Suppose you have an unordered array: {3,2,4,1}, the following is an array of partitions, dividing the arrays into {3,2} and {4,1} two arrays first. Then the two arrays are divided into the last {3},{2},{4},{1} four arrays, which are divided into complete.
Next, the array is merged, the two arrays {3} and {2} are merged into an ordered array {2,3}, and the same operation is performed on the 4,1, with {1,4}, and then merging the two ordered arrays together, and finally merging into {1,2,3,4}, the merge completes.
The merge sort algorithm is implemented in Java code as follows:
public static void MergeSort (int[] array,int head,int tail) {//Determine whether the header index of the array is less than the tail index if (Head < tail) {
int middle = (head+tail)/2;
MergeSort (Array,head,middle);
MergeSort (Array,middle+1,tail);
Merge (Array,head,middle,tail); } public static void Merge (int[] array, int head, int middle, int tail) {//TODO auto-generated method
Stub int[] temp = new Int[tail-head + 1];
int a = head;
int b = middle + 1;
int i = 0; Compares smaller values in a temporary array for the number in two arrays while (a <= middle && b <=tail) {if (Array[a] < array [b])
{temp[i++] = array[a++];
} else{temp[i++] = array[b++];
Add the number in an array that is not participating in the comparison to the temporary array while (a <= middle) {temp[i++] = array[a++];
while (b <= tail) {temp[i++] = array[b++]; ///Put the sorted array back into the array system.arraycopy (temp,0,array,head,tail-head + 1); }