代码:
package com.zhang;
public class Merge {
public void MergeSort(int data[],int left,int right) {
if(left + 1 < right ) {//递归出口,至少含有一个元素
int mid = (left + right)/2;
MergeSort(data,left,mid);
MergeSort(data,mid,right);
Merge(data,left,mid,right);
}
}
public void Merge(int data[],int left,int mid,int right) {
int i=left,j=mid,flag=left;
int temp[] = new int[data.length];
System.arraycopy(data, 0, temp, 0, data.length);//保存排序前的数组
// while(i<mid&&j<right) {
// if(temp[i]<temp[j])
// data[flag++] = temp[i++];
// else
// data[flag++] = temp[j++];
// }
// while(i<mid)
// data[flag++] = temp[i++];
// while(j<right)
// data[flag++] = temp[j++];
for(;flag<right;) {
if(j>=right|| i<mid&&temp[i] <temp[j])//将上面几个条件合在一起
data[flag++] = temp[i++];
else
data[flag++] = temp[j++];
}
}
public static void main(String[] args) {
int data[] = new int[]{9,8,7,6,5,4,3,2,1};
System.out.println("运行前:");
System.out.println(Arrays.toString(data));
new Merge().MergeSort(data, 0, data.length);
System.out.println("运行后:");
System.out.println(Arrays.toString(data));
}
运行结果:
运行前:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
运行后:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
注意点:
a,递归出口的确定