1 设计思想
- 申请空间,使其大小为两个已经排序序列之和,该空间用来存放合并后的序列;
- 设定两个指针,最初位置分别为两个已经排序序列的起始位置;
- 比较两个指针所指向的元素,选择相对小的元素放入到合并空间,并移动指针到下一位置;
- 重复(步骤 3) 直到某一指针达到序列尾;将另一序列剩下的所有元素直接复制到合并序列尾。
2 关键代码
public static void sort(int []a) {
//申请空间
int []temp=new int[a.length];
//开始排序
sort(a,0,a.length-1,temp);
}
public static void sort(int []a,int start,int last,int []tem) {
//避免跨越中线
//分
if(start<last) {
int mid=(start+last)/2;
sort(a,start,mid,tem);//第1段 ->[9 8 7 6 5]
sort(a,mid+1,last,tem);//第2段 ->[4 3 2 1 0]
merge(a,start,mid,last,tem);
}
}
//归并
public static void merge(int []a,int left,int mid,int last,int []tem) {
int i=left;
int j=mid+1;
int t=0;
while(i<=mid&&j<=last) {
if(a[i]<=a[j]) {
tem[t++]=a[i++];
}else {
tem[t++]=a[j++];
}
}
while(i<=mid) {
tem[t++]=a[i++];
}
while(j<=last) {
tem[t++]=a[j++];
}
t=0;
while(left<=last) {
a[left++]=tem[t++];
}
}
3 结果展示
博主后记:
希望看到此篇博文的网友,如果发现有什么不对的地方,欢迎在下方留言指正!博主一定虚心接受并改正!大家一起共同进步。如果对你有所帮助,可以给博主一个赞👍。