<span style="white-space:pre"> </span>private static void mergArray(int[] unsorted,int first,int mid,int last,int[] temp){
int i=first,j=mid+1;
int m=mid,n=last;
int k=0;
while(i<=m&&j<=n){
if(unsorted[i]<=unsorted[j]){
temp[k++]=unsorted[i++];
}
else{
temp[k++]=unsorted[j++];
}
}
while(i<=m){
temp[k++]=unsorted[i++];
}
while(j<=n){
temp[k++]=unsorted[j++];
}
for(i=0;i<k;i++){
unsorted[first+i]=temp[i];
}
}
private static void mergeSort(int[] unsorted,int first,int last,int[] temp){
if(first<last){
int mid=(first+last)/2;
mergeSort(unsorted,first,mid,temp);
mergeSort(unsorted,mid+1,last,temp);
mergArray(unsorted,first,mid,last,temp);
}
}
private static boolean MergSort(int[] unsorted,int n){//归并排序
int[] temp=new int[n];
if(temp==null) return false;
else{
mergeSort(unsorted,0,n-1,temp);
temp=null;
return true;
}
}
个人觉得归并算法是挺难的一种,因为它涉及到了方法的递归调用,但是如果找到一个入口点,就可以理解他,这里的入口点就是mergeSort方法。
代码分析:
1.if(first<last)是用来控制递归的,而mid=(first+last)/2是用来分割数组的,把数组分割成一个个的小数组,先是调用mergeSort(unsorted,first,mid,temp)左分割,分割到不能再分割的时候调用mergeSorted(unsorted,mid+1,last,temp)进行又分割,分割到不能再分割为止,然后调用mergArray(unsorted,fist,mid,last,temp)从后往前面逐个合并。
2.找出两个小数组中最小的值,然后放到临时数组中,最后形成一个有序的大数组。
328

被折叠的 条评论
为什么被折叠?



