用java代码写一段合并排序的程序
//合并排序
public class Hebing {
public static void mergeSort(int [] a) {
int [] b=new int[a.length];
int s=1; //开始时,让数组中的每个元素单独成为一个子数组
while(s<a.length) {
mergePass(a,b,s); //合并到数组b
s+=s; //合并一次,s就变成s+s
mergePass(b,a,s); //合并到数组a
s+=s;
}
print(a);
}
//mergePass用于合并排好序的相邻数组段
public static void mergePass(int [] x,int [] y,int s) {
int i=0;
while(i<=x.length-2*s) {
merge(x,y,i,i+s-1,i+2*s-1);
i=i+2*s;
}
if(i+s<x.length) {
merge(x,y,i,i+s-1,x.length-1);
}
else {
for(int j=i;j<x.length;j++) {
y[j]=x[j];
}
}
}
//合并c[l:m]和c[m+1:r]到d[l:r]
public static void merge(int [] c,int [] d,int l,int m,int r) {
int i=l;
int j=m+1;
int k=l;
while((i<=m)&(j<=r)) {
if(c[i]<=c[j]) {
d[k]=c[i];
i++;
k++;
}
else {
d[k]=c[j];
j++;
k++;
}
}
if(i>m) {
for(int q=j;q<=r;q++) {
d[k]=c[q];
k++;
}
}
else {
for(int q=i;q<=m;q++) {
d[k]=c[q];
k++;
}
}
}
//输出数组a
public static void print(int[] a){
for(int n=0;n<a.length;n++){
System.out.print(a[n]+" ");
}
System.out.println();
}
public static void main(String[] arg) {
int [] a= {1,5,4,55,89,46,23,75,61,2,7,9};
mergeSort(a);
}
}