package org.rev.algorithm;/** * merge sort, belongs to the Exchange sort, the time complexity is the algorithm complexity 0 (n log n), is slower than the fast sort, but stable. * * 1. recursively splits a sequence into multiple ordered sub-sequences. * * 2. recursively merges these sub-sequences into a complete subsequence. * */public class mergesort { public static void main (String[] args) { int[] data = {39, 11, 38, 97, 86, 37, 12, 4, 51, 18}; // Merge Sort mergesort ms = new mergesort (); ms.sort (data); system.out.println ("After sorting:"); ms.printdata (data); } Public void sort (Int[] data) { if (data.length > 0) { // length is 0, it cannot be reduced by 1. mergesort (data, 0, data.length - 1); &nbSp; } } public void mergesort (Int[] data, int left, int right) { if (left < right) { int middle = (left + right) / 2; system.out.println ("Left is:" + left + ", right is:" + right + ", middle is:" + middle + ", data[" + middle + "]=" + data [Middle]); mergesort (Data, left, middle); // recursion to the left mergesort (data, middle + 1, right); // recursion to the right merge (data, left, middle, right); // merge &nBsp;printdata (data); } } /** * merges two arrays, Merging the first two arrays is ordered, and the merged arrays are also ordered. * * @param data Array Objects * @param left index of the first element of the left array * @param middle The index of the last element of the left array, middle+1 is the index of the first element of the right array * @param right Index of the last element of the right array */ private void merge (int[] data, int left, int middle, int right) { // Temporary Arrays int[] tmpArr = new int[data.length]; // index of the first element on the right side int mid = middle + 1; // tmp temporary variables, caches the index of the first element of the left array int tmp = left; // third records the index of a temporary array int third = left; while (left <= middle && mid <= right) { // Select a smaller number from two arrays to put in a temporary array if (Data[left] <= data[mid]) { tmparr[third++] = data[left++]; } else { tmpArr[third++] = data[mid++]; } } // put the rest of the parts into a temporary array while (Left <= middle) { tmparr[third++] = data [left++]; } while (mid <= right) { tmpArr[third++] = data[mid++]; } // copy the temporary array back to the original array while (tmp <= right) { data[tmp] = tmpArr[tmp++]; } } /* * Print data from an output array */ private void printdata (Int[] data) { for (int i = 0; i < data.length; i++) { system.out.print (data[i] + "\ T"); } system.out.println (); }}
Merge sort (JAVA)