The content of this article is about the algorithm ideas and code for implementing quick sorting in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Core idea: Divide it into two parts according to size, sort them recursively, and look forward and backward (split function).
php code is as follows:
<?php function quickSort($arr){ $resultArr=qSort($arr,0,count($arr)-1); return $resultArr; } function qSort($arr,$low,$high){ if($low<$high){ //算出枢轴值 $partRes=partition($arr,$low,$high); $arr=$partRes["resultArr"]; $arr=qSort($arr,$low,$partRes["pivot"]-1);//对低子表递归排序 $arr=qSort($arr,$partRes["pivot"]+1,$high);//对高子表递归排序 } return $arr; } function partition($arr,$low,$high){ $pivotkey=$arr[$low]; //用子表的第一个记录作枢纽记录 while ($low<$high){ //从表的两端交替向中间扫描 while ($low<$high&&$arr[$high]>=$pivotkey){ $high--; } $arr=swap($arr,$low,$high);//将比枢轴记录小的记录交换到低端 while ($low$low,"resultArr"=>$arr);//返回枢轴所在位置 } function swap($arr,$index1,$index2){ $pivotkey=$arr[$index1]; $arr[$index1]=$arr[$index2]; $arr[$index2]=$pivotkey; return $arr; } $arr=array(9,1,3,2,6,7,4,8); $resultArr=quickSort($arr); echo implode(',',$resultArr);
Recommended related articles:
PHP Quick Sort Small Example PHP Quick Sort Implementation Method
Quick Sort PHP Implementation PHP Quick Sort Method PHP Quick Sort Ideas Quick Sort Calculation
The above is the detailed content of Algorithmic ideas and code for quick sorting in PHP. For more information, please follow other related articles on the PHP Chinese website!