1 Packagecn.it;2 3 Importjava.util.Arrays;4 //using divide and conquer thought to realize merge sort5 Public classFz {6 Public Static voidMain (string[] args) {7 inta[]={1,2,3,4,5,6,8,7,3,4,9,0};8 intTemp[] =New int[a.length];9Sortdiv (A, 0, a.length-1, temp);Ten System.out.println (Arrays.tostring (a)); One } A - Private Static voidSortdiv (int[] A,intStartintEndint[] temp) { - if(start<end) { the //Sequential traversal recursive Zuozi recursive right subtree - intMid= (start+end)/2; - Sortdiv (A, start, mid,temp); -Sortdiv (A, mid+1, end,temp); + Merge (A, start, end, mid,temp); - } + } A at Private Static voidMergeint[] A,intStartintEndintMidint[] temp) { - intI=start; - intJ=mid+1; - intK=0; - - //keep fewer people in temporary space in while(I<=mid && j<=end) { - if(a[i]<A[j]) { totemp[k++]=a[i++]; +}Else{ -temp[k++]=a[j++]; the } * } $ Panax Notoginseng //remaining joined to the end of the team - while(i<=mid) { thetemp[k++]=a[i++]; + } A the while(j<=end) { +temp[k++]=a[j++]; - } $ $ //displace an ordered temporary array back to the actual stored array - for(intl=0;l<k;l++){ -a[start+l]=Temp[l]; the } - Wuyi } the}
Divide and conquer thought--small test (merge sort follow up)