1. 程式人生 > >排序演算法之——歸併排序(兩種方法及其優化)

排序演算法之——歸併排序(兩種方法及其優化)

1 public class MergeX implements Comparable<Merge> {// 歸併排序(優化後) 2 private static Comparable[] aux; 3 4 private static boolean less(Comparable v, Comparable w) { 5 return v.compareTo(w) < 0; 6 } 7 8 @Override 9 public int compareTo(Merge arg0) { 10
// TODO Auto-generated method stub 11 return 0; 12 } 13 14 public static void merge(Comparable[] a, Comparable[] aux, int lo, int mid, int hi) {// 原地歸併的抽象方法 15 int i = lo, j = mid + 1; 16 // for (int k = lo; k <= hi; k++) { 17 // aux[k] = a[k]; 18 //
} 19 for (int k = lo; k <= hi; k++) { 20 if (i > mid) { 21 a[k] = aux[j++]; 22 } else if (j > hi) { 23 a[k] = aux[i++]; 24 } else if (less(aux[j], aux[i])) { 25 a[k] = aux[j++]; 26 } else
{ 27 a[k] = aux[i++]; 28 } 29 } 30 } 31 32 public static void sort(Comparable[] a) { 33 aux = a.clone();// 一次性分配空間 34 sort(a, aux, 0, a.length - 1); 35 } 36 37 private static void sort(Comparable[] a, Comparable[] aux, int lo, int hi) { 38 /* 39 * 自頂向下的並歸排序 三個改進 40 */ 41 // if (hi <= lo) { 42 // return; 43 // } 44 int mid = lo + (hi - lo) / 2; 45 if (hi - lo <= 7) {// 對小規模子陣列使用插入排序 46 //System.out.println("insert!"); 47 insertionSort(a, lo, hi); 48 return; 49 } 50 sort(aux, a, lo, mid); 51 sort(aux, a, mid + 1, hi); 52 if (!less(aux[mid + 1], aux[mid])) {// 已經有序時跳過merge(a中lo到mid mid到hi分別都是有序的) 53 System.arraycopy(aux, lo, a, lo, hi-lo+1); 54 return; 55 } 56 merge(a, aux, lo, mid, hi); 57 } 58 59 private static void insertionSort(Comparable[] a, int lo, int hi) { 60 for (int i = lo; i <= hi; i++) 61 for (int j = i; j > lo && less(a[j], a[j - 1]); j--) 62 exch(a, j, j - 1); 63 } 64 65 private static void exch(Comparable[] a, int j, int i) { 66 // TODO Auto-generated method stub 67 Comparable temp; 68 temp = a[j]; 69 a[j] = a[i]; 70 a[i] = temp; 71 } 72 73 public static void main(String[] args) { 74 MergeX mgx = new MergeX(); 75 Comparable a[] = { 8, 1, 6, 8, 4, 6, 9,7,1, 2, 3,4,8,5,2,6,4,3,8}; 76 mgx.sort(a); 77 for (int i = 0; i < a.length; i++) { 78 System.out.print(a[i] + " "); 79 } 80 } 81 }