今天开始学Java 排序算法之归并排序

思路:它的最直观的想法是将两个有序子序列通过从左到右两两元素相互比较的排序的方法,那么如果使两个子序列有序呢,那就再将这两个子序列两两分,一直分下去的话最后就得到长度为1的各个子序列,这时就相当于每个子序列都是有序的了,最后按照之前的最直观的想法两两比较合并。

甩上代码来:

public static void sort(int[] a,int low,int mid,int high){
int[] tmp = new int[high - low+1];
int i =low;
int j =mid+1;
int k = 0;
while(i<=mid && j<=high){
if(a[i] <a[j]){
tmp[k++] = a[i++];
}
else{
tmp[k++] = a[j++];
}
}
// if one of the block is finished
//because there is no while out of this block,so,use while insteadof if
while(i<=mid){
tmp[k++] = a[i++];
}
while(j<=high){
tmp[k++] = a[j++];
}
for (int t = 0;t<tmp.length;t++){
a[low+t] = tmp[t];
}

}
public static void GBsort(int[] a,int low,int high){
// is + not -
int mid = (high+low)/2;
if(low < high){
GBsort(a,low,mid);
GBsort(a,mid+1,high);
sort(a,low,mid,high);
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值