java 基本算法之归并排序实例代码

时间:2021-10-15 04:49:02

java 基本算法归并排序实例代码

原理:归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,

     * 即把待排序序列分为若干个子序列,每个子序列是有序的。
     * 然后再把有序子序列合并为整体有序序列。

实例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
public class MergeSort {
 
  /**
   *
   *
   *
   * @param args
   */
  public static void main(String[] args) {
    int a[] = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62,
        99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 };
 
    sort(a, 0, a.length - 1);
    System.out.println(Arrays.toString(a));
 
  }
 
  public static void sort(int[] data, int left, int right) {
    if (left < right) {
      // 找出中间索引
      int center = (left + right) / 2;
      // 对左边数组进行递归
      sort(data, left, center);
      // 对右边数组进行递归
      sort(data, center + 1, right);
      // 合并
      merge(data, left, center, right);
    }
 
  }
 
  public static void merge(int[] data, int left, int center, int right) {
    int[] tmpArr = new int[data.length];
    int mid = center + 1;
    // third记录中间数组的索引
    int third = left;
    int tmp = left;
    while (left <= center && mid <= right) {
      // 从两个数组中取出最小的放入中间数组
      if (data[left] <= data[mid]) {
        tmpArr[third++] = data[left++];
      } else {
        tmpArr[third++] = data[mid++];
      }
 
    }
 
    // 剩余部分依次放入中间数组
    while (left <= center) {
      tmpArr[third++] = data[left++];
    }
    while (mid <= right) {
      tmpArr[third++] = data[mid++];
    }
 
    // 将中间数组中的内容复制回原数组
    while (tmp <= right) {
      data[tmp] = tmpArr[tmp++];
    }
    System.out.println(Arrays.toString(data));
  }
 
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:https://my.oschina.net/songxinqiang/blog/710395