package merging;
public class MergingDigui {
public static void print(int[] arr){
for(int n=0;n<arr.length;n++){
System.out.print(arr[n]+" ");
}
System.out.println();
}
public static void fun(int[] a){
mSort(a, a, 0, a.length-1);
}
public static void mSort(int[] a, int[] b, int s, int t){
int m;
int[] c = new int[a.length];//新建一个数组来暂存
if(s==t){
b[s] = a[s];
}else{
m = (s+t)/2;
mSort(a, c, s, m);//将a分为两组,分别是c(s,m),c(m+1,t)
mSort(a, c, m+1, t);
merge(c, b, s, m, t);//将c(s,m)和c(m+1,t)归并到b
print(a);
print(b);
System.out.println();
}
}
//将a[i..m]和a[m+1..n]归并到b[]
public static void merge(int[] a, int[] b, int i, int m, int n){
int j;
int k = i;
for(j=m+1;i<=m&&j<=n;k++){
if(a[i]<a[j]){
b[k] = a[i++];
}else{
b[k] = a[j++];
}
}
while(i<=m){
b[k] = a[i];
k++;i++;
}
while(j<=n){
b[k] = a[j];
k++;j++;
}
}
public static void main(String[] args) {
int[] a={16,7,13,10,9,15,3,2,5,8,12,1,11,4,6,14};
fun(a);
print(a);
}
}
public class MergingDigui {
public static void print(int[] arr){
for(int n=0;n<arr.length;n++){
System.out.print(arr[n]+" ");
}
System.out.println();
}
public static void fun(int[] a){
mSort(a, a, 0, a.length-1);
}
public static void mSort(int[] a, int[] b, int s, int t){
int m;
int[] c = new int[a.length];//新建一个数组来暂存
if(s==t){
b[s] = a[s];
}else{
m = (s+t)/2;
mSort(a, c, s, m);//将a分为两组,分别是c(s,m),c(m+1,t)
mSort(a, c, m+1, t);
merge(c, b, s, m, t);//将c(s,m)和c(m+1,t)归并到b
print(a);
print(b);
System.out.println();
}
}
//将a[i..m]和a[m+1..n]归并到b[]
public static void merge(int[] a, int[] b, int i, int m, int n){
int j;
int k = i;
for(j=m+1;i<=m&&j<=n;k++){
if(a[i]<a[j]){
b[k] = a[i++];
}else{
b[k] = a[j++];
}
}
while(i<=m){
b[k] = a[i];
k++;i++;
}
while(j<=n){
b[k] = a[j];
k++;j++;
}
}
public static void main(String[] args) {
int[] a={16,7,13,10,9,15,3,2,5,8,12,1,11,4,6,14};
fun(a);
print(a);
}
}