6-6归并排序

归并排序


基本思想

​ 归并排序(MERGE SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer) 策略(分治法将问题分(divide)成一些小的 问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案”修补”在一起,即分而治之)。、

1621153610254

图解

1621153842463

代码实现

package com.company.sort;

/**
 * @Function :
 * date 2021/5/16 - 16:32
 * How :
 */
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);
        for ( int tempInt : arr ) {
            System.out.printf("\t"+tempInt);
        }
    }

    /**
     *
     * @param arr       原数组
     * @param left      左边界
     * @param right     有边界
     * @param temp      辅助数组
     */
    public static void mergeSort(int []arr,int left,int right,int[] temp){
        if (left<right){
            int mid = (right+left)/2;
            mergeSort(arr,left,mid,temp);
            mergeSort(arr,mid+1,right,temp);
            merge(arr,left,mid,right,temp);

        }

    }

    /**
     *合并方法
     * @param arr       源数组
     * @param left      左边边界
     * @param mid       中间边界
     * @param right     右边边界
     * @param temp      中转数组
     */
    public static void merge(int[] arr,int left,int mid, int right, int[] temp){
        int i = left;
        int j = mid+1;
        int tempIndex = 0;   //中转数组指针
        //(一)
        //将左右两边有序数组合并到temp 知道两边的有序数列有一个完成为止
        while (i<=mid && j<=right){
            if (arr[i] <= arr[j]){
                temp[tempIndex] =arr[i];
                ++i;
                ++tempIndex;
            }else {
                temp[tempIndex] =arr[j];
                ++j;
                ++tempIndex;
            }
        }
        //(二)
        //把剩余的数字填充到temp中
        while (i<=mid){
            temp[tempIndex] =arr[i];
            ++i;
            ++tempIndex;
        }

        while (j<=right){
            temp[tempIndex] =arr[j];
            ++j;
            ++tempIndex;
        }
        //(三)
        //将temp数组拷贝到原数组arr中
        tempIndex = 0;
        int tempLeft = left;
        while (tempLeft <= right){
            arr[tempLeft] = temp[tempIndex];
            tempIndex++;
            tempLeft++;
        }

    }
}

posted @ 2021-11-23 21:13  剪水行舟  阅读(84)  评论(0)    收藏  举报