这几天没事,复习下算法。写了一下归并排序。算法导论里的思想的确很好。整理下 用java实现。
不多说 直接上代码了,看官请看:
/**
* Created by Steven on 10/23/2014.
*/
public class MergeSortTest {
public static void merge(int [] a,int low,int mid ,int high){
//设置临时数组(增加一个空间 末尾最大值+∞ 为值的比较提供方便 此为1024)
int blength = (mid-low+1) +1;
int clength = (high-mid) +1;
int [] b=new int [blength];
int [] c=new int [clength];
int j=0,k=0;
for(int i=0;i<blength-1;i++){
b[i]=a[i+low];
}
for(int i=0;i<clength-1;i++){
c[i]=a[i+mid+1];
}
b[blength-1]=1024;
c[clength-1]=1024;
for(int i=low;i<=high;i++){
if(b[j]<= c[k]){
a[i] =b[j];
j++;
}else{
a[i] = c[k];
k++;
}
}
}
public static void MergeSort(int[] a, int low, int high){
int mid = (low+high)/2;
if(low < high){
MergeSort(a,low,mid);
MergeSort(a,mid+1,high);
merge(a,low,mid,high);
}
}
public static void main(String[] args) {
int []a={5,2,6,1,7,0,4,8,9,3};
for(int i:a){
System.out.print(i+" ");
}
MergeSort(a,0,a.length-1);
System.out.println();
for(int i:a){
System.out.print(i + " ");
}
}
}