码迷,mamicode.com
首页 > 其他好文 > 详细

归并排序

时间:2014-09-09 10:53:28      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   java   ar   for   数据   div   

归并排序算法稳定,数组需要O(n)的额外空间,链表需要O(log(n))的额外空间,时间复杂度为O(nlog(n))

NOTE: 新数组的创建和数据拷贝是硬伤,我尝试了一下只申请一个workspace,应该还不错吧,没有理论论证

代码:

 1 package sorts;
 2 
 3 import java.util.Arrays;
 4 import java.util.Random;
 5 
 6 public class MergeSort {
 7 
 8     public static <T extends Comparable<T>> void sort(T[] array) {
 9         T[] workspace = (T[])new Comparable[array.length]; // only 1 workspace is claimed, no more copies
10         recMerge(array, 0, array.length-1, workspace);
11     }
12     
13     /**
14      * recursively merge
15      * */
16     private static <T extends Comparable<T>> void recMerge(T[] array,
17             int lowerBound, int upperBound, T[] wp) {
18         if (lowerBound == upperBound) {
19             return;
20         } else {
21             int mid = ((lowerBound + upperBound)>>1); // (low + upper) / 2
22             recMerge(array, lowerBound, mid, wp);
23             recMerge(array, mid+1, upperBound, wp);
24             merge(array, lowerBound, mid, upperBound, wp);
25         }
26     }
27     /**
28      * Merge two sorted array into one.
29      * */
30     private static <T extends Comparable<T>> void merge(T[] array,
31             int lowerBound, int mid, int upperBound, T[] wp) {
32         int lowIndex = lowerBound;
33         int highIndex = mid + 1;
34         int j = 0; // workspace index
35         // merge them into one array
36         while (lowIndex <= mid && highIndex <= upperBound) {
37             if (array[lowIndex].compareTo(array[highIndex]) < 0) {
38                 wp[j++] = array[lowIndex++];
39             } else {
40                 wp[j++] = array[highIndex++];
41             }
42         }
43         // copy the rest
44         while (lowIndex <= mid) {
45             wp[j++] = array[lowIndex++];
46         }
47         while (highIndex <= upperBound) {
48             wp[j++] = array[highIndex++];
49         }
50         // copy the merged array into the original array
51         int n = upperBound - lowerBound + 1;
52         for (int i = 0; i < n; i++) {
53             array[lowerBound+i] = wp[i];
54         }
55     }
56     
57     // test
58     public static void main(String[] args) {
59         Random random = new Random();
60         int num = 10;
61         int bound = 100;
62         Integer[] a = new Integer[num];
63         for (int i = 0; i < num; i++) {
64             a[i] = random.nextInt(bound);
65         }
66         MergeSort.sort(a);
67         System.out.println(Arrays.toString(a));
68     }
69 
70 }

 

归并排序

标签:style   blog   color   os   java   ar   for   数据   div   

原文地址:http://www.cnblogs.com/qrlozte/p/3961334.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!