/** * @Description * @Author admin * @Date 2021/1/7 16:40 * @Version 1.0 */ public class Main01 { public static int count=0; public static void main(String[] args) { int[] arr = {1,9,3,22,10,8,4,2,99,31,3332,2,19,322,544,29,103,56}; System.out.println(arrstr(arr)); sort(arr); System.out.println(arrstr(arr)); System.out.println("count:"+count); } public static void sort(int[] arr){ int L = 0; int R = arr.length-1; process(arr,L,R);//全部有序 } public static void process(int[] arr,int L,int R){ String baselog = "process("+(L)+","+R+") "; System.out.println(arrstr(arr)+"----L:"+L+",R:"+R); if(L==R){ System.out.println(baselog+"只有一个元素L:"+L+",arr[L]:"+arr[L]); return;//只有一个元素,本身就是有序的, 表示当前分组已变成有序的了 } int M = L+((R-L)>>1); //取出中点,继续拆分 System.out.println(baselog+"M:"+M); System.out.println(baselog+"左边开始排序,范围:("+L+","+M+")"); process(arr,L,M);//左边有序 System.out.println(baselog+"右边开始排序,范围:("+(M+1)+","+R+")"); process(arr,M+1,R);//右边有序 System.out.println(baselog+"开始合并排序,范围:("+L+","+M+"],"+R+")"); merge(arr,L,M,R);//合并有序 } public static void merge(int[] arr,int L, int M, int R){ String baselog = "merge("+L+","+M+"],"+R+") "; int[] result = new int[R-L+1]; int LP = L; int RP = M+1; System.out.println(baselog+"LP:"+LP+",RP:"+RP); int i=0; while(LP<=M && RP<=R){ count++; result[i++] = arr[LP]<arr[RP]?arr[LP++]:arr[RP++]; } while (LP<=M){ count++; result[i++] = arr[LP++]; } while (RP<=R){ count++; result[i++] = arr[RP++]; } for(int k=L;k<=R;k++){ count++; arr[k]=result[k-L]; //result数组的起始位置0 对应原数据是L,原数组 比 result数组多了L的偏移 } System.out.println(baselog+"arrstr(arr):"+arrstr(arr)); System.out.println(baselog+"arrstr(result):"+arrstr(result)); } public static String arrstr(int[] arr){ StringBuffer sb = new StringBuffer(); for(int i: arr){ sb.append(String.valueOf(i)).append(" "); } return sb.toString(); } }