MergeSort
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MergeSort相关的知识,希望对你有一定的参考价值。
递归方式:
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 }
迭代方式:
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 }
以上是关于MergeSort的主要内容,如果未能解决你的问题,请参考以下文章