算法-归并排序(分治)
程序员文章站
2022-05-10 17:21:21
...
package MOOC;
public class GuiBing {
static int[] a= {13,27,19,2,8,12,2,8,30,89};
static int[] b=new int[10];
public static void main(String[] args) {
int size=a.length;
MergeSort(a,0,size-1,b); //传递的是下标
for(int i=0;i<size;i++)
System.out.print(a[i]+" ");
}
private static void MergeSort(int[] a, int s, int e, int[] temp) {
if(s<e) { //归并区间大于1
int m=s+(e-s)/2;
MergeSort(a, s, m, temp); //前一半归并排序,用temp做中转
MergeSort(a, m+1, e, temp); //后一半归并排序,用temp做中转
Merge(a,s,m,e,temp); //两半合并
}
}
private static void Merge(int[] a, int s, int m, int e, int[] temp) {
int pb=0;
int p1=s,p2=m+1;
while(p1<=m&&p2<=e) { //两个数组合并到一个
if(a[p1]<a[p2])
temp[pb++]=a[p1++];
else
temp[pb++]=a[p2++];
}
while(p1<=m)
temp[pb++]=a[p1++];
while(p2<=e)
temp[pb++]=a[p2++];
for(int i=0;i<e-s+1;i++)
a[s+i]=temp[i];
}
}