简体   繁体   English

PHP:快速排序代码一直在说:警告:array_merge():参数3不是其中的数组

[英]PHP: Quick sort code keeps saying: Warning: array_merge(): Argument #3 is not an array in

I am learning about sorting algorithms and I am trying this code: 我正在学习排序算法,并且正在尝试这段代码:

function quicksort($array){
              if(count($array) == 0){
              return array();
              }

              $pivot = $array[0];
              $left = array();
              $right = array();

                  for($i = 1; $i < count($array); $i++){
                      if($array[$i] < $pivot){
                        $left[] = $array[$i];
                      }
                      else{
                        $right[] = $array[$i];
                      }

                      return array_merge(quicksort($left), array($pivot), quicksort($right));
                  }

              }
              $sorted = quicksort($data);

However, when trying to run it - it gives me: 但是,当尝试运行它时-它给了我:

Warning: array_merge(): Argument #3 is not an array in - on line 21 警告:array_merge():参数#3不是-在第21行的-中的数组

Any reason for this? 有什么原因吗?

you're returning inside the loop, you need to move that statement outside the loop. 您将在循环内返回,则需要将该语句移到循环外。

<?php
function quicksort($array){
    if(count($array) == 0){
        return array();
    }

    $pivot = $array[0];
    $left = array();
    $right = array();

    for($i = 1; $i < count($array); $i++){
        if($array[$i] < $pivot){
            $left[] = $array[$i];
        }
        else{
            $right[] = $array[$i];
        }
        // remove return that was here
    }

    // and move it outside the loop here
    return array_merge(quicksort($left), array($pivot), quicksort($right));
}

$data = [3,4,2,1];
print_r(quicksort($data));
 Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM