package merg;
/**
* @author 真他喵的学不动咯
* @create 2022-08-18--20:04
*/
public class mergrsortwo { //归并排序,非递归版本
//边界条件
//无需排序
public static void mergedor2(int[] arr) {
if (arr == null || arr.length < 1 / 2) {
return;
}
int step = 1;
int N=arr.length;
//调整步长
while (step <= N){ //步长小于总长度
int L=0;
while (L<N){ //左组可能凑不够一步长 L....M.M+1...,R
int M=0; //讨论M
//左组
if (N-L>=step){ //N-L为剩余长度,剩余长度大于step,不越界
M=L+step-1;
}else{
M=N-1; //没step那么大,就把最后一个数N-1作为M
}
//右组
int R=0; //讨论R
if (M==N-1){ //没有右组
break;
}
if(N-1-M>step){ //没越界,剩余长度N-1-M
R=M+step;
}else{ //越界了
R=N-1;
}
//L....M.M+1...,R
merge(arr,L,M,R);
if (R==N-1){
break;
}else{
L=R+1;
}
}
if (step>N/2){ //此时,step*2>N,可能会溢出
break;
}else { //不会溢出
step*=2;
}
}
}
//合并
public static void merge(int[] arr,int L,int M,int R){
//辅助数组
int[] help =new int[R-L+1];
int i=0;
int p1=L; //左指针
int p2=M+1; //右指针
while (p1<=M&&p2<=R){ //双方没越界
help[i++]=arr[p1]<=arr[p2]? arr[p1++]:arr[p2++];
}
while (p1<=M){ //左边没越界
help[i++]=arr[p1++]; //左边剩余数全加进去
}
while (p2<=R){ //右边没越界
help[i++]=arr[p2++]; //右边剩余数全加进去
}
for (i=0;i<help.length;i++){ //左边越界
arr[L+i]=help[i]; //把help数组的内容覆盖原数组 ,i表示内容索引
}
}
}
//归并排序,非递归版本
最新推荐文章于 2024-06-05 21:00:00 发布