標籤:第一個 method public 沒有 auto 排序 gen pac pre
快速排序比插入排序快了兩個數量級
package test.sort;public class Paixu { public static void main(String[] args) { // TODO Auto-generated method stub int[] a = random(10000000); int[] b = a.clone(); long l1 = System.currentTimeMillis(); insert_Sort(b); long l2 = System.currentTimeMillis(); System.out.println("插入排序用時:"+(l2-l1)); check(b); int[] c = a.clone(); int start = 0; int end = a.length-1; long startT = System.currentTimeMillis(); quick_sort(c,start,end); long endT = System.currentTimeMillis(); System.out.println("快速排序用時:"+(endT-startT)); check(c); } // 插入排序 private static int[] insert_Sort(int[] a){ // 最佳化插入排序演算法 for(int i=1;i<a.length;i++){ int temp=a[i]; int j; // 假設 i 之前的都是有序的,i之後是無序的; for(j=i-1;j>=0;j--) { // 當前的 a[j] 比 a[i] 大,將 a[j]向後移動 if(a[j]>temp) { a[j+1]=a[j]; }else { // 當前的 a[i] 比i之前的元素都大 break; } } a[j+1]=temp; } System.out.println("***********************"); return a; } private static void quick_sort(int[] a,int low,int high){ int start = low; int end = high; int key = a[low]; while(end>start){ //從後往前比較 while(end>start&&a[end]>=key) //如果沒有比關索引值小的,比較下一個,直到有比關索引值小的交換位置,然後又從前往後比較 end--; if(a[end]<=key){ int temp = a[end]; a[end] = a[start]; a[start] = temp; } //從前往後比較 while(end>start&&a[start]<=key)//如果沒有比關索引值大的,比較下一個,直到有比關索引值大的交換位置 start++; if(a[start]>=key){ int temp = a[start]; a[start] = a[end]; a[end] = temp; } //此時第一次迴圈比較結束,關索引值的位置已經確定了。左邊的值都比關索引值小,右邊的值都比關索引值大,但是兩邊的順序還有可能是不一樣的,進行下面的遞迴調用 } //遞迴 if(start>low) quick_sort(a,low,start-1);//左邊序列。第一個索引位置到關索引值索引-1 if(end<high) quick_sort(a,end+1,high);//右邊序列。從關索引值索引+1到最後一個 }
// 產生隨機數組 public static int[] random(int num) { long start = System.currentTimeMillis(); int[] a ; a = new int[num]; for (int i = 0; i < num; i++) { int rand = (int) Math.round(Math.random()*num*100000); a[i] = rand; } long end =System.currentTimeMillis(); System.out.println("產生"+num+"個隨機數花費時間=====>"+(end-start)+"毫秒"); return a; }
// 檢驗排序結果 private static void check (int[] a) { boolean flag = true; for (int i = 0; i < a.length-1; i++) { if (a[i+1] < a[i]) { flag = false; break; } } System.out.println(flag?"排序成功":"排序失敗"); }}
java 快速排序