先明白merge,单单2个数组的排序算法;然后在写递归条件以及调用处理
package jvm;
public class Main {
public static void merge(int[] a , int first ,int mid ,int last ,int[] temp ) {
/*if(first == last)
return;*/
int i ,j;
for(i= first,j= mid +1;first<=mid &&j<=last;i++ ) {
if(a[first]>=a[j]) temp[i] = a[first++];
else temp[i] = a[j++];
}
while(first < mid ) temp[i++] = a[first++];
while(j < last ) temp[i++] = a[j++];
}
public static void mergesort(int[] a,int first ,int last ,int[] temp) {
if(first < last)//判定出栈的条件
{
int mid = (first+last)/2;
mergesort(a,first,mid,temp);
mergesort(a,mid+1,last,temp);
merge(a, first, mid, last, temp);
}
}
public static void main(String[] args) {
int[] a = {1,2,3,10,23,41,532,21};
int[] temp = new int[a.length];
if(a.length == 0)
return;
mergesort(a, 0, a.length, temp);
}
}