Merge Sort - Ideas and Implementation

       Merge sort (MERGE-SORT) is a sorting method implemented by the idea of ​​​​merging . The algorithm adopts the classic divide -and-conquer strategy (the divide-and-conquer method divides the problem into small problems and then solves them recursively. , and the conquer stage "fixes" the answers obtained in the division stage together, that is, divide and conquer).

       In merge sort, we will first find the middle subscript mid of an array, and then use this mid as the center to sort both sides respectively, and then we will re-allocate the value size according to the sorted subarrays on both sides.

Let's take the following array as an example :

         

     (1) mid is equal to the maximum subscript of the array / 2 = 3, so we take the subscript 3 (value 7) as the center, and sort the numbers 0~3 and 4~7 respectively.

     (2) At this time, the arrays on both sides can also create branches:

                                       

       (3) You can see that there are still four small arrays above, we continue to create branches:

                           

     (4) It can be seen that we can no longer continue to create branches at this time, because there is no need to sort when the number of arrays is 1. At this time, we can start sorting and merging each small array:

                               

     (5) Continue, get the small array formed in the previous step, and then combine it into a new sorted array:

                                   

     (6) Finally, the result we want is here:

                   

code show as below:

public class MergeSort {
	public static void mergeSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		mergeSort(arr, 0, arr.length - 1);
	}

	public static void mergeSort(int[] arr, int l, int r) {
		if (l == r) {
			return;
		}
		int mid = l + ((r - l) >> 1);
		mergeSort(arr, l, mid);
		mergeSort(arr, mid + 1, r);
		merge(arr, l, mid, r);
	}

	public static void merge(int[] arr, int l, int m, int r) {
		int[] help = new int[r - l + 1];
		int i = 0;
		int l1 = l;
		int r1 = m + 1;
		while (l1 <= m && r1 <= r) {
			help[i++] = arr[l1] < arr[r1] ? arr[l1++] : arr[r1++];
		}
		while (l1 <= m) {
			help[i++] = arr[l1++];
		}
		while (r1 <= r) {
			help[i++] = arr[r1++];
		}
		for (int j = 0; j < help.length; j++) {
			arr[l + j] = help[j];
		}
	}
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325108148&siteId=291194637