极客时间-排序-归并排序


public class MergeSort {
   
	/*
	 * 归并排序,依次把大小为n的数组分解求和
	 * 1.数组的起始位置p,找到元素的终止位置r=n-1,找到中间元素q=(p+r)/2,从p---q成一个分割数组a1,(q+1)---r分割成另一个数组a2
	 * 2.把数组a和数组b重复1的方式,直到p>=r时返回
	 * 3.返回时合并子数组a1和a2,申请一个大小为r+1的临时数组保存,重复2和3步骤合并
	*/
	public void mergeSort(Integer a[],int p,int r) {
		if(p>=r) {
			return ;
		}
		 int q =(r+p)/ 2;
		 mergeSort(a, p,q);//分解
		 mergeSort(a, q+1,r);//分解
		 a=mergeSortData(a,p,q,r);//合并a和b

	}
	
	public Integer[] mergeSortData(Integer a[],int p,int q,int r) {
		Integer temp[]=new Integer[r+1];
		int i=p;
		int j=q+1;
		int k=0;
		while(i<=q&&j<=r) {
			if(a[i]<a[j]){
				temp[k++]=a[i++];
			}else {
				temp[k++]=a[j++];
			}	
		}
		

		int start=i;
		int end=q;//如果分割的左边的数组还有剩余数据
		if(j<=r) {//如果分割的右边的数组还有剩余数据
			start=j;	
			end=r;
		}
		
		while(start<=end) {
			temp[k++]=a[start++];
		}
		
		for (int i1=0 ;i1<k;i1++){
			a[p+i1] = temp[i1] ;
		 }
		
		return a;
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Integer a[] = { 10, 13, 3, 7,9, 8, 10, 15, 11};
		MergeSort mergesort=new MergeSort();
		mergesort.mergeSort(a, 0,a.length-1);
		for(Integer c:a) {
			System.out.print(c+" ");
		}

	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值