3 minutes to learn merge sort

Problem-solving ideas:

  1. Decomposition: The sorted to be divided into two parts, each part sort
  2. Merge: merge the sorted part
  3. Recursion:
    1. Recursion formulas: merge_sort (p..q) = merge (merge_sort (p..r), merge_sort (r + 1..q))
    2. Termination condition: p> = q, packet 1 only elements

Algorithm

public class Solution {
    // 归并排序
    public static void mergeSort(int[] array) {
        // 递归调用
        mergeSort(array, 0, array.length - 1);
    }
    // 递归函数
    public static void mergeSort(int[] array, int start, int end) {
        // 终止条件
        if (start >= end) {
            return;
        }
        int middle = (start + end) / 2;
        // 分解
        mergeSort(array, start, middle);
        mergeSort(array, middle + 1, end);

        // 合并 array[start..middle]~array[middle+1..end]
        merge(array, start, middle, end);

    }
    // 合并两个有序数组
    public static void merge(int[] array, int start, int middle, int end) {
        // 用来存放有序元素
        int[] tempArray = new int[end - start + 1];

        // 取两个数组中的最小值放到 tempArray 中
        int index1 = start;
        int index2 = middle + 1;
        int tempIndex = 0;
        while (index1 <= middle && index2 <= end) {
            // 使用 = 保证稳定
            if (array[index1] <= array[index2]) {
                tempArray[tempIndex] = array[index1];
                index1++;
            } else {
                tempArray[tempIndex] = array[index2];
                index2++;
            }
            tempIndex++;
        }
        // 将剩余元素均放入 tempArray 中
        while (index1 <= middle) {
            tempArray[tempIndex] = array[index1];
            tempIndex++;
            index1++;
        }
        while (index2 <= end) {
            tempArray[tempIndex] = array[index2];
            tempIndex++;
            index2++;
        }
        // 将 temp 数组的有序元素放到 array 中
        for (int i = 0; i < tempArray.length; i++) {
            array[start + i] = tempArray[i];
        }
    }


    public static void main(String[] args) {
        int[] array = new int[]{2, 5, 1, 6, 9, 3};
        mergeSort(array);
        for (int i : array) {
            System.out.print(i + " ");
        }
    }
}

Published 245 original articles · won praise 16 · views 50000 +

Guess you like

Origin blog.csdn.net/qq_29150765/article/details/105189728