归并排序

归并排序

思想:

  1. 将数组不断划分,只到不可再分为止(划分阶段仅划分,不做其他任何处理);
  2. 再讲划分后的数组进行排序合并。

代码实现:

import java.util.Arrays;

public class MergeSort {
    public static void main(String[] args) {
        int[] arr = {8, 4, 5, 7, 1, 3, 6, 2};
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
        System.out.println(Arrays.toString(arr));
    }
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left < right) {
            int mid=(left+right)/2;
            //向左递归分解
            mergeSort(arr,left,mid,temp);
            //向右递归分解
            mergeSort(arr,mid+1,right,temp);
            merge(arr,left,mid,right,temp);
        }
    }
    /**
     * @Description 合并的方法
     * @param arr 待排序数组
     * @param left  左边有序序列的初始索引
     * @param mid 中间索引
     * @param right 右边索引
     * @param temp 中转数组
     */
    private static void merge(int[] arr, int left, int mid, int right,int[]temp) {
        int i=left  ;
        int j=mid+1;
        int t=0;
        //1.想把左右两边(有序数组)的数组按照规则填充到temp数组
        //知道左右两边的有序数组有一方处理完毕为止
        while (i <= mid && j <= right) {
            if (arr[i] <= arr[j]) {
                temp[t] = arr[i];
                i++;
                t++;
            }else{
                temp[t] = arr[j];
                t++;
                j++;
            }
        }
        //2.当一方处理完毕后,把没有处理完毕的剩下数据拷贝到temp数组
        while (i <= mid) {
            temp[t] = arr[i];
            t++;
            i++;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t++;
            j++;
        }
        //3.将temp数组中的全部拷贝到arr数组中
        t=0;
        while (left <= right) {
            arr[left] = temp[t];
            left++;
            t++;
        }
    }
}
posted @ 2022-09-26 15:54  与否业务NOW  阅读(16)  评论(0)    收藏  举报