publicstaticvoidselectionSort(Comparable[] a){ int N = a.length; for (int i = 0; i < N; i++) { int min = i; for (int j = i+1; j < N; j++) { if (less(a[j], a[min])) min = j; exch(a, i, min); } } }
publicstaticvoidshellSort(Comparable[] a){ int N = a.length; for (int h = N / 2; h >= 1; h = h / 2) { for (int i = h; i < N; i++) { for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) { exch(a, j, j - h); } } } }
/*归并*/ publicstaticvoidmerge(Comparable[] a, int lo, int mid, int hi){ int i = lo, j = mid + 1; for (int k = lo; k <= hi; k++) { aux[k] = a[k]; } for (int k = lo; k <= hi; k++) { if (i > mid) a[k] = aux[j++]; elseif (j > hi) a[k] = aux[i++]; elseif (less(aux[j], aux[i])) a[k] = aux[j++]; else a[k] = aux[i++]; } }
/*自顶向下*/ publicstaticvoidmergeTopSort(Comparable[] a){ aux = new Comparable[a.length]; sort(a, 0, a.length-1); }
privatestaticvoidsort(Comparable[] a, int lo, int hi){ if (hi <= lo) return; int mid = lo + (hi - lo)/2; sort(a, lo, mid); sort(a, mid+1, hi); merge(a, lo, mid, hi); }
/*自底向上*/ publicstaticvoidsort(Comparable[] a){ int N = a.length; aux = new Comparable[N]; for (int sz = 1; sz < N; sz = sz+sz) { for (int lo = 0; lo < N -sz; lo += sz+sz) { merge(a, lo, lo+sz+1, Math.min(lo+sz+sz-1, N-1)); } } } }
finalstaticintpartition(Comparable[] a, int lo, int hi){ int i = lo, j = hi + 1; Comparable v = a[lo]; while (true) { while (less(a[++i], v)) { if (i == hi) break; } while (less(v, a[--j])) { if (j == lo) break; } if (i >= j) break; exch(a, i, j); } exch(a, lo, j); return j; }
而排序算法就是使用递归的方式去调用切分的方法。
1 2 3 4 5 6
publicstaticvoidquickSort(Comparable[] a, int lo, int hi){ if (hi <= lo) return; int j = partition(a, lo, hi); quickSort(a, lo, j - 1); quickSort(a, j + 1, hi); }