咖啡猫

导航

2路归并排序

import java.util.Arrays;


public class Merge_sort {
public static void main(String[] args){
int[] nums={ 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 };
sort(nums,0,nums.length-1);
System.out.println(Arrays.toString(nums));
}

public static int[] sort(int[] num,int low,int high){
int mid=(low+high)/2;
if(low<high){ 
//左排序
sort(num,low,mid);
//右排序
sort(num,mid+1,high);
Merge(num, low,mid, high);
}
return num;
}

public static void Merge(int[] num,int low,int mid,int high){

int[] temp=new int[high-low+1];
int i=low;
int j=mid+1;
int k=0;
while(i<=mid&&j<=high){
if(num[i]<=num[j]){
temp[k]=num[i];
i++;
}else{
temp[k]=num[j];
j++;
}
k++;
}
while(i<=mid){
temp[k]=num[i];
k++;
i++;
}
while(j<=high){
temp[k]=num[j];
k++;
j++;
}

for(int m=0;m<temp.length;m++){
num[low++]=temp[m];

}
}

}

posted on 2015-03-27 21:09  咖啡猫1292  阅读(132)  评论(0编辑  收藏  举报