//利用递归,实现序列的二分,再排序,合并,排序合并同时进行
//合并时需要定义一个同样长度的空数组,用于存放排好序的序列
//主要是实现合并函数
//合并时需要定义一个同样长度的空数组,用于存放排好序的序列
//主要是实现合并函数
import java.util.*;
import java.io.*;
public class GuiBingSort{
void merge(int[] a, int first,int last,int center){//first是数组起始位置,last是末尾位置,center是中间位置
int[] a1=new int[a.length];//定义一个新数组,存放排好的数
int temp=first;
int i=first;
int mid=center+1;
while(first<center && mid<last){//两段进行比较,小的依次放到新数组里
if(a[first]<a[mid]){
a1[temp++]=a[first++];
}
else{
a1[temp++]=a[mid++];
} //这样比完后会有其中一个数组有元素剩余,另一个全放到了a1中
} //
while(first<center){//如果此时first仍小于center,说明前半个数组元素剩余
a1[temp++]=a[first++];//把剩余的直接放到a1中(因为已经排好序)
}
while(mid<last){
a1[temp++]=a[mid++];//把剩余的直接放到a1中(因为已经排好序)
}
while (i<=last){
a[i]=a1[i++];
}
}
void digui(int[] a, int first, int last){//进行递归操作
if(first<last){
int center=(first+last)/2;
digui(a, first, center); //对左边数组进行递归
digui(a, center+1,last); //对右边数组进行递归
merge(a,first,last,center); //合并
}
}
public static void main(String[] args){
int a[]={49,38,65,97,76,13,27,49,78,34,12,6};
int i;
GuiBingSort A=new GuiBingSort();//必须实例化类,才能调用其方法
A.digui(a,0,a.length-1);
for(i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
}