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

WBOY
Release: 2016-06-06 20:45:16
Original
988 people have browsed it

<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>
Copy after login
Copy after login

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

回复内容:

<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>
Copy after login
Copy after login

一般我看到这种代码面试第一关就通不过。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>
Copy after login
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!