归并排序--稳定

归并排序--稳定


归并排序是一个稳定(当有两个相同数字的时候,不会改变这两个数字的前后顺序)的排序算法。主要是通过递归将一组数组的值进行两两拆分,然后比较,然后复制到一组临时数组中,再将临时数组的值按顺序替换原来数组的值。

    public static void merge(int[] arr, int start, int mid,int end){
    
    
        int i = start; //左边遍历起点 
        int j = mid+1; //右边遍历起点
        int[] tmp = new int[end-start+1];  //临时数组
        int tmp_i = 0; //临时数组起点坐标

        while (i<=mid&&j<=end){
    
      //左边从起点到mid,右边mid+1到end遍历,两边一起开始遍历
            if (arr[i]<arr[j]){
    
     //把小的放入数组如果右边比左边大,就先把小的左边放入临时数组
                tmp[tmp_i++] = arr[i++];//把小的,左边放入数组
            }else {
    
    
                tmp[tmp_i++] = arr[j++]; //把小的右边放入数组
            }
        }
        while (i<=mid){
    
     上面遍历完后,左边还有值没放入数组,直接放
            tmp[tmp_i++] = arr[i++];
        }
        while (j<=end){
    
    上面遍历完后,右边还有值没放入数组,直接放
            tmp[tmp_i++] = arr[j++];
        }
        for (i=0; i<tmp_i;++i){
    
     //遍历临时数组,替换原数组
            arr[start++] = tmp[i];
        }
    }
    public static void merger_up_todown(int[] arr, int start, int end){
    
    
        if (start<end){
    
    //递归结束条件
            int mid= (start+end)/2;
            merger_up_todown(arr,start,mid); //递归左边
            merger_up_todown(arr,mid+1,end);//递归右边
            merge(arr,start,mid,end);//合并
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_43859562/article/details/121905950