Algorithm description: For a given set of records, first merge every two adjacent subsequences of length 1 to obtain n/2 (rounded upwards) ordered subsequences of length 2 or 1, and then merge them in pairs, and repeat this process until an ordered sequence is obtained.
package sorting;/** * Merge sort* Average O(nlogn), best O(nlogn), worst O(nlogn); space complexity O(n); stable; more complex* @author zeng * */public class MergeSort {public static void merge(int[] a, int start, int mid, int end) {int[] tmp = new int[a.length];System.out.println("merge " + start + "~" + end);int i = start, j = mid + 1, k = start;while (i != mid + 1 && j != end + 1) {if (a[i] < a[j]) tmp[k++] = a[i++]; else tmp[k++] = a[j++];}while (i != mid + 1) tmp[k++] = a[i++];while (j != end + 1) tmp[k++] = a[j++];for (i = start; i <= end; i++) a[i] = tmp[i];for (int p : a) System.out.print(p + " ");System.out.println();}static void mergeSort(int[] a, int start, int end) {if (start < end) {int mid = (start + end) / 2;mergeSort(a, start, mid);// Ordered mergeSort(a, mid + 1, end);// Ordered merge(a, start, mid, end);}}public static void main(String[] args) {int[] b = { 49, 38, 65, 97, 76, 13, 27, 50 };mergeSort(b, 0, b.length - 1);}}Let’s take a look at the results of the operation:
Summarize
The above is all the content of this article about the simple implementation of merge sorting of Java sorting algorithms. I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!