標籤:
其基本思路應該是排成兩部分單獨記錄,確定樞軸,實施樞軸到左側值我們都小於樞軸值。樞軸向右大於樞軸值。這樣子不斷遞迴下去
function quicksort(arr,low,high){ var pivot; if(low < high){ pivot = partition(arr,low,high); quicksort(arr,low,pivot-1); quicksort(arr,pivot+1,high); } return arr; }
這個就是快排的入口函數。出現了partition方法。它的作用就是找出記錄中的keyword,也就是樞軸
function partition(arr,low,high){ 1. var pivot = arr[low]; 2. while(low <= high){ 3. while(low <= high && arr[high] >= pivot){ 4. high--; 5. } 6. swap(arr,low,high); 7. while(low <= high && arr[low] < pivot){ 8. low++; 9. } 10 swap(arr,low,high); 11 } 12 return low; 13 }
事實上它的思想也是挺簡單的。比方你有這樣一系列數字:5 1 9 3 7 4 8 6 2。我們這裡僅僅計算第一趟快排,其它僅僅是遞迴下去,思路是一致的。
- 程式碼1把數字列的第一個元素5作為為樞軸,跟最後一個元素2比較;
- 一比較不符合程式碼3 arr[high] >= pivot。所以就運行交換兩個位置的值;
- 如今的數字列為2 1 9 3 7 4 8 6 5
- 運行程式碼7得出2 1都小於樞軸5繼續迴圈,可是到了9時就不滿足條件退出了迴圈。
- 運行交換後數字列為2 1 5 3 7 4 8 6 9
- 這個時候low為3 high為9 滿足程式碼2的迴圈條件繼續依照前面步驟1~5運行
- 最後第一趟數字列為2 1 4 3 5 7 8 6 9
- 樞軸5的左邊的值2 1 4 3都比它小。右邊的值7 8 6 9都比它大
最後有一個函數就是交換函數的
function swap(arr,low,high){ var temp; temp = arr[low]; arr[low] = arr[high]; arr[high] = temp; }
這個函數實現起來還是比較簡單的
假設不太瞭解快排方法的人能夠去看《大話資料結構》,寫得淺顯易懂。
還有就是事實上能夠用閉包的方法封裝partition和swap方法,揭露quicksort介面到該方法向外界
著作權聲明:本文部落格原創文章,部落格,未經同意,不得轉載。
javascript實現快速排