归并排序

 1 public class guiBing {
 2     private static void MergeSort(int[] a,int start,int end){
 3         if(start < end){
 4             //找分割位置
 5             int middle = (end + start) / 2;
 6             //递归分割下去,左边,右边
 7             MergeSort(a,start,middle);
 8             MergeSort(a,middle + 1,end);
 9             //该合并了
10             merge(a,start,middle,end);
11         }
12     }
13 
14     public static void merge(int[] list,int start,int middle,int end){
15         //leftLength和rightLength分别表示左边序列和右边序列的长度。左边从start开始包括middle,右边从middle+1开始
16         int leftLength = middle - start + 1;
17         int rightLength = end - middle;
18         //定义俩个空的容器,将list分为左、右俩个序列,便于最后的排序
19         int L[] = new int[leftLength];
20         int R[] = new int[rightLength];
21         //定义下标:L、R、list
22         int lIndex = 0;
23         int rIndex = 0;
24         int listIndex = 0;
25 
26         //赋值 L 和 R
27         for (lIndex = 0,listIndex = start; lIndex < leftLength; lIndex++,listIndex++) {
28             L[lIndex] = list[listIndex];
29         }
30 
31         for (rIndex = 0,listIndex = middle + 1; rIndex < rightLength; rIndex++,listIndex++) {
32             R[rIndex] = list[listIndex];
33         }
34 
35         //弟兄们,我要开始合体了,小的给我排前面去
36         for(lIndex = 0,rIndex = 0,listIndex = start;
37             lIndex < leftLength && rIndex < rightLength;
38             listIndex++){
39             //谁小谁先放进list中
40             if(L[lIndex] <= R[rIndex]){
41                 list[listIndex] = L[lIndex];
42                 lIndex++;
43             } else {
44                 list[listIndex] = R[rIndex];
45                 rIndex++;
46             }
47         }
48         //将 L/R中 剩下的元素 放入 list,另外下面这俩个if,只会执行一个
49         if(lIndex < leftLength){
50             for (int tempIndex = lIndex; tempIndex < leftLength; tempIndex++,listIndex++) {
51                 list[listIndex] = L[tempIndex];
52             }
53         }
54 
55         if(rIndex < rightLength){
56             for (int tempIndex = rIndex; tempIndex < rightLength; tempIndex++,listIndex++) {
57                 list[listIndex] = R[tempIndex];
58             }
59         }
60     }
61 
62     public static void main(String[] args) {
63         int i=0;
64         int a[] = {5,4,9,8,7,6,0,1,3,2};
65         int len = a.length;
66         MergeSort(a,0,len-1);
67         for(i=0; i<len; i++){
68             System.err.print(a[i]+" ");
69         }
70     }
71 }

 

posted @ 2021-01-04 02:00  peanut_zh  阅读(66)  评论(0编辑  收藏  举报