ホームページ  >  記事  >  バックエンド開発  >  PHP写的归并排序。谁能看的懂?。。。

PHP写的归并排序。谁能看的懂?。。。

WBOY
WBOYオリジナル
2016-06-06 20:45:16988ブラウズ

<code class="lang-php"><br> <?php function  merge($frist=array(),$second=array(),$attribute=''){
       $key=0;
       $c=0;
       $d=0;
        $temp=array();
        for($a=0;$a<count($frist);$a++){


            for($b=$c;$b<count($second);$b++){
            if($frist[$a]<=$second[$b]){
                $d++;
                $temp[$key]=$frist[$a];
                 $key++;
                 break;
            }
            else{
                $c++;
            $temp[$key]=$second[$b];
            $key++;

            }

            }
        }

    if($frist[$d-1]<=$second[$c-1]){
        for($d;$d<count($frist);$d++){
            array_push($temp, $frist[$d]);
        }
    }
    else{
 for($b;$b<count($second);$b++){
            array_push($temp, $second[$b]);
        }
    }
     return $temp;

    }
$f=array(1,2,3,4,5,6,9,10,100,101);
$s=array(1,2,3,4,8,20,21,22,300);
$sf=merge($f,$s);
print_r($sf);
</code></code>

这个问题已被关闭,原因:无法获得确切结果的问题

回复内容:

<code class="lang-php"><br> <?php function  merge($frist=array(),$second=array(),$attribute=''){
       $key=0;
       $c=0;
       $d=0;
        $temp=array();
        for($a=0;$a<count($frist);$a++){


            for($b=$c;$b<count($second);$b++){
            if($frist[$a]<=$second[$b]){
                $d++;
                $temp[$key]=$frist[$a];
                 $key++;
                 break;
            }
            else{
                $c++;
            $temp[$key]=$second[$b];
            $key++;

            }

            }
        }

    if($frist[$d-1]<=$second[$c-1]){
        for($d;$d<count($frist);$d++){
            array_push($temp, $frist[$d]);
        }
    }
    else{
 for($b;$b<count($second);$b++){
            array_push($temp, $second[$b]);
        }
    }
     return $temp;

    }
$f=array(1,2,3,4,5,6,9,10,100,101);
$s=array(1,2,3,4,8,20,21,22,300);
$sf=merge($f,$s);
print_r($sf);
</code></code>

一般我看到这种代码面试第一关就通不过。first拼错、代码格式不规范、$f,$s,$sf是什么东西?这种代码首先就不是容易让人看懂,何谈维护和理解

有点晕,看了一会发现,好像合并过程中带着冒泡排序的意思

<code class="lang-php">$arrayA=array(1,3,2,4,5,6,9,10,100,101);
$arrayB=array(1,2,3,103,7,8,20,21,22,300);

$arrayMerge=array_merge($arrayA,$arrayB);
function bubbleSort($array){
    $count=count($array);
    for($i=0;$i</code>
声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。