Thinking
As shown below, for an array of s = {11,18,20,11,6,8}, select key 11 as a key, and then select two guards low and high, respectively starting from the head portion and the tail portion of the array, perform the following operations :
- Analyzing loop element is greater than the tail where the sentinel key, and low <high, if the sentinel High-, the cycle continues; Otherwise, the cycle is stopped, s [low] = s [high], then go to 2.
- Determining the cycle where the sentinel header element is less than or equal key, and the low <high, if the sentinel low ++, the cycle continues; Otherwise, the cycle is stopped, s [high] = s [low], then go to 3.
- If low> = high, cycle stop, otherwise go to 1.
C ++ implementation
int partion(vector<int>& s, int low, int high) {
int key = s[low];
while(low < high) {
while(low < high && s[high] > key)
high--;
s[low] = s[high];
while(low < high && s[low] <= key)
low++;
s[high] = s[low];
}
s[low] = key;
return low;
}
void quickSort(vector<int>& s, int low, int high) {
if(low >= high) return;
int index = partion(s, low, high);
quickSort(s, low, index - 1);
quickSort(s, index + 1, high);
}
to sum up
- The optimal situation is to time to take the entire array elements exactly equally, i.e., T [n] = 2T [n / 2] + f (n). In this case the optimal complexity of O (nlogn).
- The worst case time complexity is accessible to every element in the array is minimum or maximum, this situation is equivalent to the bubble sort, i.e. T [n] = n (n -1). In this case the worst case time complexity of O (n ^ 2);
- The average time complexity is O (nlogn).
- First-place quicksort space used is O (1); while the real consumption space is recursive calls, since each recursive want to save some data; optimal space case complexity is O (logn); worst- space case complexity is O (n).