package coretext;
public class MergeSort {
public static void main(String[] args) {
int []arr = {2,5,3,6,8,4,9,1};
MergeText a =new MergeText();
int [] array =a.MS(arr, 8);
for(int i=0;i<8;i++) {
System.out.println(array[i]);
}
}
}
class MergeText{
//归并排序
public int[] MS(int A[],int n) {
MSort(A,A,0,n-1);
return A;
}
//把一个数组分解成两个分段
public void MSort(int A[],int B[],int s,int t){
if(s==t) {
B[s]=A[s];
}
else {
int n;
n=(s+t)/2;
int [] C= new int[100];
MSort(A,C,s,n);
MSort(A,C,n+1,t);
merge(C,B,s,n,t);
}
}
//把两个分段合并成一个数组
public void merge(int A[],int B[],int i,int m,int n) {
int j,k; //k即是用来遍历A的又是来标记B
for(j=m+1,k=i;i<=m && j<=n;k++) {
if(A[i]<A[j])
B[k]=A[i++];
else
B[k]=A[j++];
}
if(i<=m) {
while(i<=m)
B[k++]=A[i++];
}
if(j<=n) {
while(j<=n)
B[k++]=A[j++];
}
}
}
测试结果为:
12345689.