概念
什么是快排?
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:通過一趟排序將要排序的數據分割成獨立的兩部分,其中一部分的所有數據都比另外一部分的所有數據都要小,然后再按此方法對這兩部分數據分別進行快速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。 ----百度百科
快排是一種比較算法,能夠對任何類型的數據進行排序,只要類型存在“小于”的關系定義。快排采用分而治之的策略,每一次排序,都選擇一個數作為支點,然后將大于支點數的放在支點數后,小于支點數的置于支點數前。對支點數前后兩部分數據重復執行之前過程,直至整個數組有序。支點數的選擇有多種策略,可以總是選擇最后一個數,或第一個數,或任意選擇數組中的某一個數,或選擇數組的中位數。
總是選擇最后一個數作為支點數的代碼: (in C++)
// Always pick the last one as the pivot
int partition(vector<int>& vec, int low, int high){
int pivot = vec[high]; // pivot element
int i = low - 1; // smaller element index
for(int j = low; j < high; j++){
// if current element is less than or equal to the pivot
if(vec[j] <= pivot){
i++;
if(i != j) swap(vec[i],vec[j]);
}
}
swap(vec[i+1],vec[high]);
return i+1;
}
// Using Recursion
void quickSort(vector<int>& vec, int low, int high){
if(low < high){
int pi = partition(vec,low,high);
// Separately sort elements before
// partition and after partition
quickSort(vec, low, pi - 1);
quickSort(vec, pi + 1, high);
}
}
// Iteratively with Stack
void quickSort(vector<int>& vec, int low, int high){
stack<int> s;
s.push(low);
s.push(high);
while(!s.empty()){
high = s.top();
s.pop();
low = s.top();
s.pop();
int pi = partition(vec,low,high);
// Separately sort elements before
// partition and after partition
if(pi - 1 > low){
s.push(low);
s.push(pi-1);
}
if(pi + 1 < high){
s.push(pi+1);
s.push(high);
}
}
}
分析:
時間復雜度:
T(n) = T(k) + T(n-k-1) + Θ(n)
n為數組大小,k為小于pivot的數字個數。
- worst case: 此種情況發生在總是選擇最小或最大的數作為pivot。如總是選擇最后一個數作為pivot的情形下,當數組本身已經是sorted情況不過是倒序時,時間復雜度是O(n*n)。
- best case: 當總是選擇middle元素作為支點數的情形,時間復雜度是O(n*Logn)。