归并排序

稳定性:稳定排序算法 

时间复杂度: 速度仅次于快速排序,T(n)=O(n*logn)

 1 import java.util.Arrays;
 2 
 3 public class MergeSort {
 4 
 5     /**
 6      * 归并排序:将两个(或两个以上)有序表合并成一个新的有序表 即把待排序序列分为若干个子序列,
 7      * 每个子序列是有序的。然后再把有序子序列合并为整体有序序列
 8      * @param args
 9      */
10     public static void main(String[] args) {
11         int[] a = { 24, 12, 65, 100, 34, 11, 23, 76, 34 };
12         int low = 0;
13         int high = a.length - 1;
14         System.out.println("排序前:" + Arrays.toString(a));
15         sort(a, low, high);
16         System.out.println("排序后:" + Arrays.toString(a));
17     }
18 
19     /**
20      * 将排好序的数组进行归并
21      * @param a 待排序数组
22      * @param low 数组起始位置
23      * @param mid 数组中间
24      * @param high 数组末尾
25      */
26     public static void merge(int[] a, int low, int mid, int high) {
27         int[] temp=new int[high-low+1];
28         int i=low,j=mid+1,k=0;
29         while(i<=mid&&j<=high){
30             if(a[i]<a[j]){
31                 temp[k++]=a[i++];
32             }else{
33                 temp[k++]=a[j++];
34             }
35         }
36         while(i<=mid){
37             temp[k++]=a[i++];
38         }
39         while(j<=high){
40             temp[k++]=a[j++];
41         }
42         for(int x=0;x<temp.length;x++){
43             a[low+x]=temp[x];
44         }
45     }
46 
47     /**
48      * @param a
49      * @param low
50      * @param high
51      * @author wangpan
52      */
53     public static void sort(int[] a, int low, int high) {
54         int mid = (low + high) / 2;
55         if (low < high) {
56             sort(a, low, mid);
57             sort(a, mid + 1, high);
58             merge(a, low, mid, high);
59         }
60     }

61 } 

posted @ 2014-09-17 16:24  第七感  阅读(114)  评论(0)    收藏  举报