PHP 两个有序数组合并成一个有序数组

<?php

    $a = [1,3,5,7,9,11];

    $b = [2,4,6,8,10];

    function test_sort($a,$b){

        $c = [];
        $aCount = count($a);
        $bCount = count($b);
        $i = $j = 0;

        while($i < $aCount && $j < $bCount){
            if($a[$i] > $b[$j]){
                $c[] = $b[$j];
                $j++;
            }elseif($a[$i] < $b[$j]){
                $c[] = $a[$i];
                $i++;
            }else{
                $c[] = $a[$i];
                $c[] = $b[$j];
                $i++;
                $j++;
            }
        }

        while($i < $aCount){
            $c[] = $a[$i];
            $i++;
        }

        while($j < $bCount){
            $c[] = $a[$j];
            $j++;
        }

        return $c;
    }


    function test_sort2($a,$b){

        $c = [];
        $aCount = count($a);
        $bCount = count($b);
        $i = $j = 0;


        while($i < $aCount || $j < $bCount){

            if($i < $aCount && $j < $bCount){
                if($a[$i] > $b[$j]){
                    $c[] = $b[$j];
                    $j++;
                }elseif($a[$i] < $b[$j]){
                    $c[] = $a[$i];
                    $i++;
                }else{
                    $c[] = $a[$i];
                    $c[] = $b[$j];
                    $i++;
                    $j++;
                }
            }elseif($i < $aCount && $j >= $bCount){
                $c[] = $a[$i];
                $i++;
            }elseif($i >= $aCount && $j < $bCount){
                $c[] = $b[$j];
                $j++;
            }

        }

        return $c;

    }

    $res = test_sort2($a,$b);

    print_r($res);

分类:   程序积累  / 
标签:   算法
 /  浏览量:  252
2021-4-12 10:56 Monday