PHP algorithm quick sort

不言
Release: 2023-03-23 09:44:01
Original
2516 people have browsed it

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

Related recommendations:

PHP Algorithm Bucket Sorting

The above is the detailed content of PHP algorithm quick sort. 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!