Merge_Sort

public class Merge_Sort {
    public static void merge(int a[],int n){
        int source; //合并之前数组的大小
        int target=1;//合并之后数组的大小
        int index;//合并的数组的起始位置
        
        while (target < n){ //如果合并之后的数组长度没有超过总的数组长度
            source = target; //本次合并的数组的长度等于上次两个数组合并之后的长度
            target = source * 2; //本次合并之后的数组的长度等于合并之前的数组的长度的两倍
            index = 0;         //数组的起始位置
            
            while((index + target) < n){//如果数组的起始位置加上合并后的长度比数组的长度短 则进行合并
                sort(a,index,index+source,index+target); //合并
                index += target;//起始位置后移
            }
            if((index + source) < n){ //如果最后一段 无法分成均等的两组
                sort(a,index,index+source,n); //合并
            }
        }
    }
    
    public static void sort(int a[],int index,int boundary1, int boundary2){
        int i = index;
        int j = boundary1;
        int temp[] = new int[boundary2-index];
        int k = 0;
        
        while(i< boundary1 && j < boundary2){
            if(a[i] < a[j]){
                temp[k++] = a[i++];
            }else{
                temp[k++] = a[j++];
            }
        }
        
        while(i < boundary1){
            temp[k++] = a[i++];
        }
        
        while(j < boundary2){
            temp[k++] = a[j++];
        }
        
        for(int m = 0; m < temp.length; m++){
            a[index+m] = temp[m];
        }
    }
    public static void main(String[] args){
        int[] a = {8,5,3,9,11,6,4,1,10,7,2};
        merge(a,a.length);
        for(int i : a){
            System.out.println(i);
        }
    }
}

 

转载于:https://www.cnblogs.com/sirhuoshan/p/3439425.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值