Merge sort, is a kind of stable sort, uses the idea of divide and conquer, divides an array into half, sorts it separately, then merges into a new array.
The code is implemented as follows:
Import Java.util.arrays;public class MergeSort {public static int[] Sort (int[] nums, int. Low, int.) { int mid = (low + high)/2; if (Low < high) {//left sort (nums, low, mid); Right sort (nums, mid + 1, high); Merge merges Around (Nums, low, Mid, high); } return nums; public static void Merge (int[] nums, int. Low, int mid, Int. high) {int[] temp = new Int[high-low + 1]; int i = low;//left pointer int j = mid + 1;//right pointer int k = 0; Move the smaller number first to the new array while (I <= mid && J <= High) {if (Nums[i] < nums[j]) { temp[k++] = nums[i++]; } else {temp[k++] = nums[j++]; }}//Move the left remaining number into the array while (I <= mid) {temp[k++] = nums[i++]; }//Move the remaining number in the right side into the array while (J < = high) {temp[k++] = nums[j++]; }//Overwrite the number in the new array with the Nums array for (int k2 = 0; K2 < temp.length; k2++) {nums[k2 + low] = temp[ K2]; }}//merge sort implementation public static void main (string[] args) {int[] array1 = {2, 7, 8, 3, 1, 6, 9, 0, 5, 4}; Mergesort.sort (array1, 0, array1.length-1); System.out.println (arrays.tostring (array1)); Int[] Array2 = {9, 1, 5, 3, 4, 2, 6, 8, 7}; Mergesort.sort (array2, 0, array2.length-1); System.out.println (arrays.tostring (array2)); } }
Data structure--the realization of merging sort