归并排序 迭代版

1 篇文章 0 订阅
1 篇文章 0 订阅

自学记录


public class MergeSort {
    public static void main(String[] args){
        int[] b={4,4,1,2,-9,10,101,2,23,9,-40,13,14,5,-8,2,1};
        mergeSort(b);
        SortTest.show(b);
    }
    public static void mergeSort(int[] a){
        int low,mid,high,step=1,len=a.length;
        //step不能大于等于区间长度,只能小于;
        while (step<len){
            low=0;//从头开始找
            // low +step-1+1<=length-1,保证high存在,若连长度为到mid为1的high值都越界了,就不执行循环,例如 (0,1),(2,3),4
            while (low+step<len){
                mid=low+step-1;
                high=mid+step;//mid+1+step-1
                if(high>len-1){ //high别越界了
                    high=len-1;
                }
                merge(a,low,mid,high);
                low=high+1;
            }
            step*=2;//一步两,两步四个...
        }

    }
    public static void merge(int[] arr, int low, int mid ,int high){
        int i=low,j=mid+1,k=0;
        int[] temp = new int[high-low+1];//临时矩阵;
        while (i<=mid && j<=high){
            if(arr[i]<=arr[j]){         //比较大小;
                temp[k++]=arr[i++];
            }
            else{
                temp[k++]=arr[j++];
            }
        }
        while(i<=mid){
            temp[k++]=arr[i++];//把剩下的补齐
        }
        while (j<=high){
            temp[k++]=arr[j++];
        }
        for(i=low,k=0;i<=high;i++,k++){
            arr[i]=temp[k];//写回去;
        }
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值