归并排序

 1 package sort;
 2 //归并排序
 3 public class MergeSortTest {
 4     public static void main(String[] args){
 5         int[] data = new int[]{5, 3, 6, 2, 1, 9, 4, 8, 7};
 6         mergeSort(data);
 7         System.out.println("排序后的数组:");
 8         print(data);
 9     }
10     
11     public static void mergeSort(int[] data){
12         sort(data, 0, data.length-1);
13     }
14     
15     public static void sort(int[] data, int left, int right){
16         if (left >= right)
17             return;
18         int center  = (left + right) / 2;
19         sort(data, left, center);
20         sort(data, center+1, right);
21         merge(data, left, center, right);
22         print(data);
23     }
24     
25     public static void merge(int[] data, int left, int center, int right){
26         //临时数组
27         int[] tempArr = new int[data.length];
28         //右边数组的第一个元素索引
29         int mid = center + 1;
30         //tempIndex记录临时数组的索引
31         int tempIndex = left;
32         //缓存左数组的第一个元素的索引
33         int tmp = left;
34         
35         while(left <= center && mid <=right){
36             if (data[left] <= data[mid]){
37                 tempArr[tempIndex++] = data[left++];
38             }else{
39                 tempArr[tempIndex++] = data[mid++];
40             }
41         }
42         
43         //剩余部分依次放入临时数组(实际上两个while只会执行其中一个)
44         while (mid <= right){
45             tempArr[tempIndex++] = data[mid++];
46         }
47         
48         while (left <= center){
49             tempArr[tempIndex++] = data[left++];
50         }
51         
52         //将临时数组中的内容拷贝回原数组中
53         while (tmp <= right){
54             data[tmp] = tempArr[tmp++];
55         }
56     }
57     
58     public static void print(int[] data){
59         for(int i=0; i<data.length; i++){
60             System.out.print(data[i]+" ");
61         }
62         System.out.println();
63     }
64 }

 

posted @ 2017-11-14 09:44  四季万花筒  阅读(154)  评论(0编辑  收藏  举报