Algorithmic ideas and code for quick sorting in PHP

不言
Release: 2023-04-03 19:14:02
Original
1327 people have browsed it

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!