How it works
- Divide: Partition the array into two subarrays around a pivot x such that elements in lower subarray ≤ x ≤ elements in upper subarray.
 - Conquer: Recursively sort the two subarrays.
 - Combine: Trivial.
 
How to divide
(Assume the array is start at p and end at q)
1. First gives two pointer i j , i point at -1, j point at p, make the pivot randomly or array[p] for some simple cases.(we assume it's array[p] now)
2. For loop by j from 0 to q.
3. In the loop:check if array[j] <= pivot .if true then add i it self then exchange array[i] and array[j] , false then continue. don't forget add j itself.
4. Out the loop:exchange array[p] (the pivot) and array[i], return i.
Lucky or unlucky
Worst case is that the array is already sorted , and the T(n) goes as Θ(n2) , in this case we'd better chose insertion sort.
Best case is that every time we divide, the subarray is already divided by some random guy.In this case T(n) is Θ(nlgn).
Average case is hard to discribe, T(n) is also Θ(nlgn).
It's a little pain to talk about the T(n) of random quick sort,just gives some conclusions.
- Quicksort is a great general-purpose sorting algorithm.
 - Quicksort is typically over twice as fast as merge sort.
 - Quicksort can benefit substantially from code tuning.
 - Quicksort behaves well even with caching and virtual memory.
 
Example code in php. (seems like there is no pointer in javascript , so I test this algorithm in php).
function partition($a,$p,$q) { $pivot = $a[$p]; if(count($a) == 1) return $a; $i = $p - 1; for($j = $p,$k = $q; $j < $k; $j++) { if($a[$j] <= $pivot) { $i++; $buf = $a[$j]; $a[$j] = $a[$i]; $a[$i] = $buf; } } $a[$p] = $a[$i]; $a[$i] = $pivot; return $i; } function quickSort($a,$p,$q) { if(!($p < $q)) return $a; $i = partition(&$a,$p,$q); quickSort(&$a,$p,$i-1); quickSort(&$a,$i+1,$q); }
                    
                
                
            
        
浙公网安备 33010602011771号