归并排序(java实现)
1 public static void sort(int[] a,int low,int high){ 2 int mid = (low+high)/2; 3 if(low<high){ //最小单元不为1时继续拆分 4 sort(a,low,mid); //拆分左边 5 sort(a,mid+1,high); //拆分右边 6 //合并 7 merge1(a, low, mid+1, high); 8 } 9 return; 10 } 11 public static void merge1(int[]a,int low,int mid,int high) { 12 int[]temp = new int[high-low+1]; 13 14 int i = low,j = mid,k =0; //拆分后比较存入临时数组 15 while(i<mid&&j<=high) { 16 if(a[i]<a[j]) { 17 temp[k++] = a[i++]; 18 }else { 19 temp[k++] = a[j++]; 20 } 21 } 22 while(i<mid) { //左边剩余的 23 temp[k++] = a[i++]; 24 } 25 26 while(j<=high) { //右边剩余的 27 temp[k++] = a[j++]; 28 } 29 for(i =0;i<temp.length;i++) { //替换掉 30 a[i+low] = temp[i]; 31 } 32 }
测试:
1 public static void main(String[] args) { 2 int[]a = {1,3,5,8,3,12,6,9}; 3 sort(a,0,7); 4 for(int i=0;i<a.length;i++) { 5 System.out.print(a[i]+" "); 6 } 7 }
结果: