public class Test {
static int a[]={49,38,65,100,32,40,12,5,6,21};
public static void main(String[] args){
sort(a,0,a.length-1);
for(int i : a){
System.out.println(i);
}
}
public static void sort(int[] data,int left,int right){
if(left<right){
int middle = (left+right)/2;
sort(data,left,middle);//对左边进行拆分
sort(data,middle+1,right);//对右边进行拆分
merge(data,left,middle,right);//合并左右两边的数据
}
}
public static void merge(int[] data, int left, int middle, int right) {
int[] temparr = new int[a.length];//用一个新数组暂时存放左右两边最小的数
//赋值暂时变量,用于遍历
int r = middle+1;//右边从middle+1开始遍历
int l = left;
int temp = left;
while(l<=middle&&r<=right){
//把小的数复制到新数组
if(data[l]<data[r]){
temparr[temp++] = data[l++];
}else{
temparr[temp++] = data [r++];
}
}
//把剩余的数复制到新数组
while(l<=middle){
temparr[temp++] = data[l++];
}
while(r<=right){
temparr[temp++] = data[r++];
}
//把新数组排序好的元素复制回原数组
while(left<=right){
data[left] = temparr[left++];
}
}
}
08-17
08-17
08-17