Home  >  Article  >  Backend Development  >  PHP quicksort quick sorting method example

PHP quicksort quick sorting method example

小云云
小云云Original
2018-03-10 09:18:281462browse

This article mainly shares with you examples of the quicksort method in PHP, hoping to help you better understand how to use quicksort.

<?phpfunction quickSort($arr){
    //先判断是否需要继续进行
    $length = count($arr);    if ($length <= 1) {        return $arr;
    }    //选择第一个元素作为基准
    $base_num = $arr[0];    //遍历除了标尺外的所有元素,按照大小关系放入两个数组内

    //初始化两个数组
    $left_array = [];   //小于基准的
    $right_array = [];  //大于基准的

    for ($i = 1; $i < $length; $i++) {        if ($base_num > $arr[$i])            //放入左边数组
            $left_array[] = $arr[$i];        else
            //放入右边
            $right_array[] = $arr[$i];

    }    //再分别对左边和右边的数组进行相同的排序处理方式递归调用这个函数
    $left_array = quickSort($left_array);    $right_array = quickSort($right_array);    //合并
    return array_merge($left_array, array($base_num), $right_array);
}$arr1 = [1, 4, 5, 8, 2, 12, 23, 17];$arr2 = quickSort($arr1);

var_dump($arr2);

Related recommendations:

php bubble, selection, insertion and quick sort algorithm sharing

Js quick sort method Example

Example of how to implement quick sort in PHP

The above is the detailed content of PHP quicksort quick sorting method example. 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