归并排序
算法效率(O(N*LogN))优于冒泡,选择以及插入排序(O(N*N)),这里的实现效率不高,生成了大量临时数组,对于理解比较容易。
public class Main {
public static void main(String[] args) {
int [] a = {9,8,7,6,5,4,3,2,1};
int [] b = mergeSort(a) ;
for (int i:b)
System.out.println(i);
}
//将有序数组a和b合并到数组c中
private static int [] merge(int [] a, int [] b){
int [] c = new int[a.length + b.length] ;
int i=0,j=0,m=0 ;
while(i<a.length && j<b.length)
{
if (a[i] < b[j])
c[m++] = a[i++];
else
c[m++] = b[j++];
}
if (i < a.length)
while(i<a.length)
c[m++] = a[i++];
if (j < b.length)
while(j < b.length)
c[m++] = b[j++];
return c ;
}
private static int [] mergeSort(int [] a){
if ( a.length == 1)
return a ;
else
{
int [] p1 = mergeSort(Arrays.copyOfRange(a, 0, a.length/2 ));
int [] p2 = mergeSort(Arrays.copyOfRange(a, a.length/2, a.length ));
return merge(p1,p2);
}
}
}