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

MergeSort

时间:2016-09-09 20:36:55      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

递归方式:

技术分享
 1 public static Object[] mergeSort(Object[] o) {
 2     o = o.clone();
 3     mergeSort(o, 0, o.length - 1);
 4     return o;
 5 }
 6 
 7 private static void mergeSort(Object[] o, int l, int r) {
 8     if (r > l) {
 9         int mid = (l + r) >>> 1;
10         mergeSort(o, l, mid);
11         mergeSort(o, mid + 1, r);
12         merge(o, l, mid, r);
13     }
14 }
15 
16 @SuppressWarnings({ "unchecked", "rawtypes" })
17 private static void merge(Object[] o, int l, int mid, int r) {
18     Object[] temp = new Object[o.length];
19     int lp = l;
20     int rp = mid + 1;
21     int tp = l;
22     while (lp <= mid && rp <= r) {
23         Comparable c = (Comparable) o[lp];
24         if (c.compareTo(o[rp]) <= 0)
25             temp[tp++] = o[lp++];
26         else
27             temp[tp++] = o[rp++];
28     }
29     while (lp <= mid)
30         temp[tp++] = o[lp++];
31     while (rp <= r)
32         temp[tp++] = o[rp++];
33     while (l <= r)
34         o[l] = temp[l++];
35 }
View Code

 

迭代方式:

技术分享
 1 public static void loopMergeSort(Object[] array) {
 2     int len=array.length;
 3     for(int step=1; step<len; step<<=1){
 4         int s2 = step<<1;
 5         for(int i=0; i<len; i+=s2){
 6             int r=i+s2-1;
 7             int mid=(i+r)>>>1;
 8             if(mid>=len)
 9                 mid=len-1;
10             if(r>=len)
11                 r=len-1;
12             merge(array, i, mid, r);
13         }
14         
15     }
16 }
View Code

 

MergeSort

标签:

原文地址:http://www.cnblogs.com/upside-down/p/5857893.html

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