三向切分的快速排序和優化

壹頁書發表於2016-09-22


  1. public class Sort{
  2.     public static void main(String[] args){
  3.         Integer[] data={100,20,21,28,22,26,80,33,3,2,9,8,7,10,77,66,99,96,91,94};
  4.         BaseSort s=new Quick3Way(data);

  5.         s.show(data);

  6.         System.out.println(s.isSorted(data));
  7.     }
  8. }



  9. class Quick3Way extends BaseSort{
  10.     public Quick3Way(Comparable[] data){
  11.         sort(data,0,data.length-1);
  12.     }

  13.     @Override
  14.     void sort(Comparable[] data, int lo, int hi) {
  15.         if(hi<=lo){
  16.             return;
  17.         }
  18.         int lt=lo,i=lo+1,gt=hi;
  19.         Comparable v=data[lo];
  20.         while(i<=gt){
  21.             int cmp=data[i].compareTo(v);
  22.             if(cmp<0) {
  23.                 exch(data, lt++, i++);
  24.             }else if(cmp>0){
  25.                 exch(data,i,gt--);
  26.             }else{
  27.                 i++;
  28.             }
  29.         }
  30.         sort(data,lo,lt-1);
  31.         sort(data,gt+1,hi);
  32.     }
  33. }
  34. abstract class BaseSort {
  35.     abstract void sort(Comparable[] data,int lo,int hi);

  36.     //比較
  37.     public boolean less(Comparable v,Comparable w){
  38.         return v.compareTo(w)<0;
  39.     }

  40.     //列印
  41.     public void show(Comparable[] data){
  42.         for(int i=0;i<data.length;i++){
  43.             System.out.print(data[i]+" ");
  44.         }
  45.         System.out.println("");
  46.     }

  47.     //驗證
  48.     public boolean isSorted(Comparable[] data){
  49.         for(int i=1;i< data.length;i++){
  50.             if(less(data[i],data[i-1]) )
  51.                 return false;
  52.         }
  53.         return true;
  54.     }

  55.     //交換
  56.     public void exch(Comparable[] data,int i,int j){
  57.         Comparable t=data[i];
  58.         data[i]=data[j];
  59.         data[j]=t;
  60.     }
  61. }

if(hi<=lo){ return; }
小陣列可以改為插入排序。
int M=5;  if(hi<=lo+M){
    Insertion.sort(data,lo,hi);  return;  }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-2125329/,如需轉載,請註明出處,否則將追究法律責任。

相關文章