1 public Integer[] merge(Integer[] a,int p,int q,int r){ 2 int n1 = q-p+1; 3 int n2 = r-q; 4 Integer[] left = new Integer[n1]; 5 Integer[] right = new Integer[n2]; 6 for(int i = 0; i<a.length; i++){ 7 if(i<n1){ 8 left[i] = a[i]; 9 }else { 10 right[i-n1] = a[i]; 11 } 12 } 13 int i=0; 14 int j=0; 15 for(int k = 0; k<a.length; k++){ 16 //当left循环完毕 17 if(i == n1){ 18 //right也循环完毕 19 if(j == n2-1){ 20 break; 21 } 22 for(;k<a.length;k++,j++){ 23 a[k] = right[j+1]; 24 } 25 break; 26 //当right循环完毕 27 }else if(j == n2){ 28 //left也循环完毕 29 if(i == n1-1){ 30 break; 31 } 32 for(;k<a.length;k++,i++){ 33 a[k] = left[i+1]; 34 } 35 break; 36 } 37 //算法的中心思想 38 if(left[i]>right[j]){ 39 a[k] = right[j]; 40 j++; 41 }else{ 42 a[k] = left[i]; 43 i++; 44 } 45 } 46 return a; 47 }
归并排序重点:多个问题分解成多个小问题(分治),由上而下形成递归求解;