標籤:ted 數組 false static sort system ++ alt []
public class TestMain { public static void main(String[] args) { Integer[] a = new Integer[5000]; for (int i = 0; i < a.length; i++) { int temp = (int)(StdRandom.random()*10000); a[i] = temp; } Integer[] b = new Integer[5000]; for (int i = 0; i < b.length; i++) { b[i] = a[i]; } //產生兩個相同的隨機數組 Stopwatch timer2 = new Stopwatch(); ToSort.insertsort(b); System.out.println(timer2.elapsedTime()); //比較兩種排序啟動並執行時間 Stopwatch timer = new Stopwatch(); ToSort.shellsort(a); System.out.println(timer.elapsedTime()); }}class ToSort{ /* * 插入排序 * 時間複雜度O(N^2) N為數組長度 */ public static void insertSort(Comparable[] a) { for (int i = 1; i < a.length; i++) { //從 1項開始,遞增項數,將前 i 項進行排序 //int temp = (int) a[i]; int j; for ( j = i; j > 0 && less(a[j] /*如果改為右移這裡則改為 temp*/, a[j-1]); j--) { //前 i-1 項為已排好序的數組,將第 i 項與 i-1 項比較,比前面的小則交換兩項,然後繼續比較 i-1 和 i-2 //例子:1,4,8,3 排序後將 3 插入到了 4 前面 1,3,4,8 exch(a, j, j-1); //這裡將交換改為右移可以提高速度 a[j] = a[j-1]; } //a[j] = temp; } } /* * 希爾排序 */ public static void shellSort(Comparable[] a) { int T = a.length; int h = 1; while(h<T/3) h = h*3 + 1; //使用 1, 4, 13, 40, 121這個希爾序列 while (h >= 1) { //當 h 為 1 時,其實就是插入排序,但前面的工作可以使整個過程變快 for (int i = h; i < T; i++) { //按當前間隔 h 進行比較,從第一個數開始每隔 h 取一個數,組成數組,進行排序。 for (int j = i; j >= h && less(a[j], a[j-h]) ; j -= h) { exch(a, j, j-h); } } h = h/3; } } /* * 判斷是否v < w */ private static boolean less(Comparable v, Comparable w) { return v.compareTo(w) < 0; //+1則false,-1則true } /* * 交換a[i]與a[j]的值 */ private static void exch(Comparable[] a, int i, int j) { Comparable t = a[i]; a[i] = a[j]; a[j] = t; } /* * 列印出數組 */ public static void show(Comparable[] a) { for (Comparable comparable : a) { System.out.print(comparable+" "); } System.out.println(); } /* * 判斷數組是否有序 */ public static boolean isSorted(Comparable[] a) { for (int i = 1; i < a.length; i++) { if (less(a[i], a[i-1])) return false; } return true; }}
希爾排序
插入排序與希爾排序Java實現