我写的php快速排序函数输出有些问题,帮忙看看

WBOY
Release: 2016-06-06 20:18:05
Original
1082 people have browsed it

<code>function qsort($arr){
    if(!isset($arr[1])){
        return $arr;
    }
    for ($i=0; $i =$arr[0]){
            $rarr[] = $arr[$i+1];
        }

    }

    $larr = qsort($larr);
    $larr[] = $arr[0];
    $rarr = qsort($rarr);
    return array_merge($larr,$rarr);

}

print_r(qsort(array(411,21,333,666)));</code>
Copy after login
Copy after login

输出Array ( [0] => [1] => [2] => 21 [3] => 333 [4] => 411 [5] => 666 )

为什么前面多了2个空值?

回复内容:

<code>function qsort($arr){
    if(!isset($arr[1])){
        return $arr;
    }
    for ($i=0; $i =$arr[0]){
            $rarr[] = $arr[$i+1];
        }

    }

    $larr = qsort($larr);
    $larr[] = $arr[0];
    $rarr = qsort($rarr);
    return array_merge($larr,$rarr);

}

print_r(qsort(array(411,21,333,666)));</code>
Copy after login
Copy after login

输出Array ( [0] => [1] => [2] => 21 [3] => 333 [4] => 411 [5] => 666 )

为什么前面多了2个空值?

for循环的结束条件是$i

然后你一定是关了报错,所以PHP没有报错,而是认为结果是空值继续执行下去了,所以排序的结果中混入了空值

正确:

<code class="php"><?php function qsort($arr){
    if(!isset($arr[1])){
        return $arr;
    }
    
    $larr = $rarr = array(); //初始化变量,确保它一定存在
    for ($i=1; $i < count($arr); $i++) { //不用$i+1,而是修改初始值为1
        if($arr[$i]<$arr[0]){
            $larr[] = $arr[$i];
        }
        if($arr[$i]>=$arr[0]){
            $rarr[] = $arr[$i];
        }

    }

    $larr = qsort($larr);
    $larr[] = $arr[0];
    $rarr = qsort($rarr);
    return array_merge($larr,$rarr);

}

print_r(qsort(array(411,21,333,666)));</code>
Copy after login

https://3v4l.org/CIKED

<code>    function querySort($arr,$order='asc') {
        if (count($arr) $value) {
            if ($order=='desc') {
                if ($value  $val) {
                    $arr_left[] = $value;
                } else {
                    $arr_right[] = $value;
                }
            }
        }

        $arr_left = querySort($arr_left,$order);
        $arr_right = querySort($arr_right,$order);

        return array_merge($arr_left,[$val],$arr_right);
    }


    $arr = querySort(array(411,21,333,666));

    echo "<pre class="brush:php;toolbar:false">";
    var_dump($arr);
Copy after login

应该是array_merge的原因

为啥要这样写排序呢? 内置的数组排序函数可以用啊!

Related labels:
php
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!