Home  >  Article  >  Backend Development  >  Algorithmic ideas and code for quick sorting in PHP

Algorithmic ideas and code for quick sorting in PHP

不言
不言Original
2018-08-14 17:15:451353browse

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).

Algorithmic ideas and code for quick sorting in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn