归并排序 mergeSort

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);
        }
    }

    public static void merge(int[] arr,int left,int mid,int right,int[] temp){
        //定义左边指针指向左边的第一个数
        int i = left;
        //定义右边指针指向右边的第一个数
        int j = mid + 1;
        //定义临时数组的指针指向第一个位置
        int t = 0;
        //当左边指针在中间范围和右边指针在数组长度范围时进行循环
        while (i <= mid && j <= right){
            //如果左边的值小于右边的值,则临时数组中加入左边的值,左边指针和临时数组指针向右移动一位
            if (arr[i] <= arr[j]){
                temp[t] = arr[i];
                i++;
                t++;
            } else { //如果右边的值小于左边的值,则临时数组中加入右边的值,右边指针和临时数组指针向右移动一位
                temp[t] = arr[j];
                j++;
                t++;
            }
        }
        //上边循环走完之后,有可能左边或者右边有剩余的,将剩余的全部加到临时数组中
        while (i <= mid){
            temp[t] = arr[i];
            i++;
            t++;
        }
        while (j <= right){
            temp[t] = arr[j];
            j++;
            t++;
        }
        //将临时数组放回原数组
        t = 0;
        int tempLeft = left;
        while (tempLeft <= right){
            arr[tempLeft] = temp[t];
            t++;
            tempLeft++;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/gg649940992/article/details/110238543