This article mainly introduced the PHP fast sort quicksort realization method, combined with the example form analysis the fast sorting principle and the PHP realizes the quick sorting the related operation skill, needs the friend to refer to the next
The example in this paper describes the PHP quick sort quicksort. Share to everyone for your reference, as follows:
Quicksort
In the fast sorting algorithm, divide-and-conquer strategy is used. First, the sequence is divided into two sub-sequences, recursively ordering the subsequence until the entire sequence is sorted. (that is, thinking in Split)
The steps are as follows:
Select a key element in the sequence as the axis;
The sequence is reordered to move elements smaller than the axis to the front of the axis, and elements larger than the axis are moved to the rear of the axis. After the division, the axis is in its final position;
Recursively reorder two sub-sequences: sub-sequences containing smaller elements and subsequence with larger elements.
such as sequence $arr:
5 3 0 11 44 7 23 2 Set the first element $arr[0] = 5 as the axis setting the flag bit low ... top represents the end of the tail
2 3 0 11 44 7 23 2 compare from opposite direction (right): 2<5 replace first position with 2,low++
2 3 0 11 44 7 23 11 compare from the opposite direction (left) until: 5<11 replaces the last position with 11,top–
Repeat the above steps until the low = = Top replaces the position with the axis element, which is 5
2 3 0 5 44 7 23 11
This can be divided into two parts 2 3 0 and 44 23 11
This allows you to proceed to the beginning of the recursion step
Algorithm implementation:
class quick_sort{function quicksort (& $arr, $low, $top) {if ($low < $top) {$pivotpos = $this->partition ($arr, $low, $top); $this->quicksort ($arr, $low, $pivotpos-1); $this->quicksort ($arr, $pivotpos +1, $top); }} function partition (& $arr, $low, $top) {if ($low = = $top) {return; }//Set initial value $com = $arr [$low]; while ($low! = $top) {//will replace smaller than the initial value to the left while ($top && $top! = $low) {if ($com > $arr [$top]) { $arr [$low + +] = $arr [$top]; Break }else{$top--; }}//will replace larger than the initial value to the right while ($low && $low! = $top) {if ($com < $arr [$low]) {$a rr[$top--] = $arr [$low]; Break }else{$low + +; }}} $arr [$low] = $com; return $low; }}