merge sort
算法导论–第二章 merge sort java代码实现
1 public class Sort { 2 public static void main(String[] args){ 3 int[] arr = new int[]{8,30,19,1,45,3,6}; 4 System.out.println("before sort: "); 5 printarr(arr); 6 mergesort(arr,0,arr.length-1); 7 System.out.println("merge sort result: "); 8 printarr(arr); 9 System.out.println(); 10 } 11 12 //归并排序 13 //采用分治的思想,递归调用,分成两份,每份各自排序,然后再合并结果;合并时采用三个指针 14 private static void mergesort(int[] arr,int start,int end) { 15 if(end>start){ 16 int divide = (start+end)/2; 17 mergesort(arr,start,divide); 18 mergesort(arr,divide+1,end); 19 merge(arr,start,end,divide); 20 } 21 } 22 private static void merge(int[] arr,int start,int end,int divide) { 23 //三个指针的初始化 24 int i = 0; 25 int j = 0; 26 int k = start; 27 //创建左右子数组,并赋值 28 int lsize = divide-start+1; 29 int rsize = end-divide; 30 int[] arrL = new int[divide-start+1]; 31 int[] arrR = new int[end-divide]; 32 for(int n =0;n<lsize;n++){ 33 arrL[n] = arr[n+start]; 34 } 35 for(int n =0;n<rsize;n++){ 36 arrR[n] = arr[n+divide+1]; 37 } 38 //三个指针移动,进行合并 39 while(k<end+1){ 40 if(arrL[i]<arrR[j]){ 41 arr[k]=arrL[i]; 42 k++; 43 i++; 44 if(i>=lsize) 45 break; 46 }else{ 47 arr[k]=arrR[j]; 48 k++; 49 j++; 50 if(j>=rsize) 51 break; 52 } 53 } 54 //把剩余的都填进arr 55 while(i<lsize){ 56 arr[k]=arrL[i]; 57 k++; 58 i++; 59 } 60 while(j<rsize){ 61 arr[k]=arrR[j]; 62 k++; 63 j++; 64 } 65 System.out.print(" 本次递归的结果:"); 66 printarr(arr); 67 } 68 public static void printarr(int[] arr){ 69 for(int i = 0;i<arr.length;i++){ 70 if(i!=arr.length-1){ 71 System.out.print(arr[i]+","); 72 }else{ 73 System.out.print(arr[i]); 74 System.out.println(); 75 } 76 77 } 78 } 79 }
运行结果:
before sort: 8,30,19,1,45,3,6 本次递归的结果:8,30,19,1,45,3,6 本次递归的结果:8,30,1,19,45,3,6 本次递归的结果:1,8,19,30,45,3,6 本次递归的结果:1,8,19,30,3,45,6 本次递归的结果:1,8,19,30,3,6,45 本次递归的结果:1,3,6,8,19,30,45 merge sort result: 1,3,6,8,19,30,45