Basic algorithm thought: The simple can say that the original sequence is divided into two sequences, and then the two sequences are ordered sequence, and finally merge the two ordered sequences, also known as two-way merge; (in the last level of recursion to ensure that the left and right two sequences each have an element, these two elements are easy to order, Recursively, their parent sequences are easy to order, and finally the whole sequence is ordered.
Packagesort;Importjava.io.IOException; Public classmergesort{ Public Static voidMain (string[] args) {int[] A =New int[] {20, 30, 90, 40, 70, 110, 60, 10, 100, 50, 80, 9, 8, 7, 6 }; MergeSort mergesort=Newmergesort (); mergesort. Sort (A,0, A.length-1); for(inti:a) {System.out.println (i);} } Public voidSort (int[] Arrays,intLeft_index,intRight_index) {if(Left_index < Right_index)//when left_index = = Right_index description is a single element, no further downward recursion{inti =Left_index;intj =Right_index;intM = (i + j)/2; Sort (arrays, I, M); Sort (arrays, M+ 1, Right_index); Merger (arrays, I, M, j);//until we find two immediate elements.}} voidMerger (int[] Array,intLeftintMidintRight ) {//merging ordered queues on the left and right sides of the same arrayinti =Left ;intm =mid;intj = mid+1;intK=0;int[] temp =New int[Right-left+1]; while(I <= m && j<=Right ) {//find the smallest element from the left and right side into the temp queueif(Array[i] <= array[j]) temp[k++] = array[i++];if(Array[i] > Array[j]) temp[k++] = array[j++]; }//I <= m description J points to the queue element has all entered temp while(I <=m) {Temp[k+ +] = array[i++];}//j<= Right Description J points to the queue element has all entered temp while(J <=Right ) {Temp[k+ +] = array[j++];}//ordinal left to right element, reset to row element for(k = 0; K < temp.length;k++) {Array[left+ K] =temp[k];} }}
Sort within-merge sort