The content introduced in this article is the quick sort code in the PHP algorithm. Now I share it with you. Friends in need can also refer to it. Let’s take a look together.
<?php //快速排序 function quicksort($arr) { //结束条件 //判断当前数组是否需要排序 if(count($arr)<=1){ return $arr; } $num = $arr[0]; //进行排序 定义标尺 $left_array = []; //左边数组 $right_array = [];//右边数组 for($i = 1;$i<count($arr);$i++){ if($num>$arr[$i]){ $left_array[] = $arr[$i];//比当前数小放到左边数组 } else { $right_array[] = $arr[$i];//比当前数大放到右边数组 } } //递归 调用自身 $left_array = quicksort($left_array); $reght_array = quicksort($right_array); //合并数组 返回排序好的数组 return array_merge($left_array,array($num),$reght_array); } //需要排序的数组 $arr = array(2,3,5,6,9,8,4,1); //调用递归 print_r(quicksort($arr));
Related recommendations:
The above is the detailed content of PHP algorithm quick sort. For more information, please follow other related articles on the PHP Chinese website!