排序算法之归并排序

概念

排序类的算法,有很强的实践需求,是非常基础的一类算法。在找工作面试中,排序算法也是大概率出现。本文将讲述排序常用的算法:归并排序,快速排序和插入排序。

归并排序

假如有一组乱序序列:a1, a2, a3 ... an,现在要将它从小到大的排序。

思想

  1. 如果排序的序列长度为1,则返回
  2. 将a1 ... an拆分为两个序列: a1...an/2, an/2 +1 .... an
  3. 递归对a1...an/2排序,递归对 an/2 +1 .... an排序
  4. 合并3步的两个有序序列的结果

案列

待排序列:1, 23, 3, 4, 8, 9,7
拆分归并如下图。可以看到,相当于树从下往上处理。


拆分归并图

代码

···

public void testMergeSort() {
    int[] from = {1, 23, 3, 4, 8, 9, 7};
    mergeSort(from, 0, from.length - 1);
    Arrays.stream(from).forEach(System.out :: println);
}


public void mergeSort(int[] from, int start, int end) {
    if (start >= end) {
        return;
    }

    int mid = (end + start) / 2;
    mergeSort(from, start, mid);
    mergeSort(from, mid + 1, end);
    merge(from, start, mid, end);
}

/**
 *
 *
 * @param from
 * @param low the begin position for from and to
 * @param mid the mergeFrom1 end position
 * @param high the merge from2 end position
 */
public void merge(int[] from, final int low, final int mid, final int high) {
    int firstPosition = low;
    int firstEndPosition = mid;
    int secondPosition = mid + 1;
    int secondEndPosition = high;

    int length = high - low + 1;
    int[] to = new int[high - low + 1];
    int i = 0;

    while (i <= length - 1) {
        if (firstPosition <= firstEndPosition && secondPosition <= secondEndPosition) {
            if (from[firstPosition] > (from[secondPosition])) {
                to[i ++] = from[secondPosition ++];
            } else {
                to[i ++] = from[firstPosition ++];
            }
        } else if (firstPosition <= firstEndPosition) {
            to[i ++] = from[firstPosition ++];
        } else if (secondPosition <= secondEndPosition) {
            to[i ++] = from[secondPosition];
        }
    }
    System.arraycopy(to, 0, from, low, length);
}

···

你可能感兴趣的:(排序算法之归并排序)