1<?PHP2 //Quick Sort3 functionPartition (&$arr,$low,$high)4 {5 $pivotkey=$arr[$low];6 while($low<$high) {7 while($low<$high&&$arr[$high] >=$pivotkey) {8 $high--;9 }Ten $temp=$arr[$low]; One $arr[$low] =$arr[$high]; A $arr[$high] =$temp; - while($low<$high&&$arr[$low] <=$pivotkey) { - $low++; the } - $temp=$arr[$low]; - $arr[$low] =$arr[$high]; - $arr[$high] =$temp; + } - return $low; + } A at /** - * @param $arr array - * @param $low Data Sort starting position (subscript) - * @param $high data sort End position (subscript) - */ - functionQuick_sort (&$arr,$low,$high) in { - if($low<$high) { to $pivot= Partition ($arr,$low,$high); +Quick_sort ($arr,$low,$pivot-1); -Quick_sort ($arr,$pivot+ 1,$high); the } * } $ Panax Notoginseng $arr=Array(10,9,8,7,6,5); -Quick_sort ($arr, 3,4); the Echo' <pre> '; + foreach($arr as $v) { A Echo $v.‘ <br/> '; the}
The algorithm is implemented by the recursive return of the method, its efficiency depends largely on the selection of reference elements, can choose the intermediate elements of the array, you can randomly get three elements, and then select the middle element (three number median method).
Another thing is that when we split up, if the length of the split sub-sequence is small (less than 5 to 20), the efficiency of the recursive sorting is not as fast as the insertion sort or the hill sort. So you can judge the length of the array, if it is less than 10, directly with the insertion sort, instead of recursively calling this quick sort.
The
writes out a sort algorithm (to write out the code) and says how to optimize it.