Home >Backend Development >PHP Tutorial >PHP algorithm quick sort

PHP algorithm quick sort

不言
不言Original
2018-04-08 13:13:062570browse

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:

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!

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