java算法之三快速排序(交換排序)

快速排序的基本思想

         通過一趟排序將待排序記錄分割成獨立的兩部分,其中一部分記錄的關鍵字均比另一部分關鍵字小,則分別對這兩部分繼續進行排序,直到整個序列有序。

       先看一下這幅圖:


把整個序列看做一個數組,把第零個位置看做中軸,和最後一個比,如果比它小交換,比它大不做任何處理;交換了以後再和小的那端比,比它小不交換,比他大交換。這樣循環往復,一趟排序完成,左邊就是比中軸小的,右邊就是比中軸大的,然後再用分治法,分別對這兩個獨立的數組進行排序。

    

[html] view plaincopy
  1. public int getMiddle(Integer[] list, int low, int high) {  
  2.         int tmp = list[low];    //數組的第一個作爲中軸  
  3.         while (low < high) {  
  4.             while (low < high && list[high] > tmp) {  
  5.                 high--;  
  6.             }  
  7.             list[low] = list[high];   //比中軸小的記錄移到低端  
  8.             while (low < high && list[low] < tmp) {  
  9.                 low++;  
  10.             }  
  11.             list[high] = list[low];   //比中軸大的記錄移到高端  
  12.         }  
  13.         list[low] = tmp;              //中軸記錄到尾  
  14.         return low;                   //返回中軸的位置  
  15.     }  

       遞歸形式的分治排序算法:

      

[html] view plaincopy
  1. public void _quickSort(Integer[] list, int low, int high) {  
  2.         if (low < high) {  
  3.             int middle = getMiddle(list, low, high);  //將list數組進行一分爲二  
  4.             _quickSort(list, low, middle - 1);        //對低字表進行遞歸排序  
  5.             _quickSort(list, middle + 1, high);       //對高字表進行遞歸排序  
  6.         }  
  7.     }  

  
[html] view plaincopy
  1. public void quick(Integer[] str) {  
  2.         if (str.length > 0) {    //查看數組是否爲空  
  3.             _quickSort(str, 0, str.length - 1);  
  4.         }  
  5.     }  

   編寫測試方法:

 

[html] view plaincopy
  1. public class TestMain {  
  2.   
  3.     /**  
  4.      * @param args  
  5.      */  
  6.     public static void main(String[] args) {  
  7.         // TODO Auto-generated method stub  
  8.          Integer[] list={34,3,53,2,23,7,14,10};  
  9.          QuicSort qs=new QuicSort();  
  10.          qs.quick(list);  
  11.          for(int i=0;i<list.length;i++){  
  12.              System.out.print(list[i]+" ");  
  13.          }  
  14.          System.out.println();  
  15.     }  
  16.   
  17. }  
     看一下打印結果吧:

     2 3 7 10 14 23 34 53 
    

     這樣就排序好了,快速排序是對【冒泡排序】的一種改進,主要是引入了分治思想的概念。平均時間複雜度是O(nlogn)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章