归并排序

名词解释:——来自百度百科

  归并排序(MERGE-SORT)是建立在归并操作上的一种有效的排序算法,该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。将已有序的子序列合并,得到完全有序的序列;即先使每个子序列有序,再使子序列段间有序。若将两个有序表合并成一个有序表,称为二路归并

 1 public class MergeSort {
 2     public static void main(String[] args) {
 3         int[] arr = {100, 30, 70, 20, 80, 60, 40, 50, 90, 10};
 4         mergeSort(arr, 0, arr.length - 1);
 5         System.out.println("排序结果:" + Arrays.toString(arr));
 6     }
 7 
 8     private static void merge(int[] arr, int low, int middle, int high) {
 9         // 创建一个新的新的数组,与传入数组大小一致
10         int[] temp = new int[high - low + 1];
11         // 定义左指针,从最低位开始
12         int i = low;
13         // 定义右指针,从中间位向右偏移一位
14         int j = middle + 1;
15         int k = 0;
16         // 左右指针同时移动,把较小的数先移到新数组中
17         while (i <= middle && j <= high) {
18             if (arr[i] < arr[j]) {
19                 temp[k++] = arr[i++];
20             } else {
21                 temp[k++] = arr[j++];
22             }
23         }
24         // 把左边剩余的数移入新数组
25         while (i <= middle) {
26             temp[k++] = arr[i++];
27         }
28         // 把右边边剩余的数移入新数组
29         while (j <= high) {
30             temp[k++] = arr[j++];
31         }
32         // 新数组覆盖原数组
33         for (int k2 = 0; k2 < temp.length; k2++) {
34             arr[k2 + low] = temp[k2];
35         }
36     }
37 
38     private static void mergeSort(int[] arr, int low, int high) {
39         // 定义源数组中间位置的索引
40         int middle = (low + high) / 2;
41         if (low < high) {
42             // 左边
43             mergeSort(arr, low, middle);
44             // 右边
45             mergeSort(arr, middle + 1, high);
46             // 左右归并
47             merge(arr, low, middle, high);
48             System.out.println(Arrays.toString(arr));
49         }
50     }
51 }
如发现有错误欢迎指正,欢迎交流,接受反驳。 -- by不为 :)
原文地址:https://www.cnblogs.com/buwei/p/10080671.html