Home > php教程 > php手册 > php 合并两个有序数组

php 合并两个有序数组

WBOY
Release: 2016-06-13 10:51:17
Original
1154 people have browsed it

对于两个有序数组,每个数组都是循环一次,即可有序的排列到新的数组里面;
采取主意递增,比较,然后按顺序插入,php代码:
[php] 
$arr1 = array(1,2,3,4,5,6,7,8);//示例数据 
$arr2 = array(3,4,5,7,9,10); 
echo '

'; <br>
print_r(mergeOrderly($arr1,$arr2));//示例 <br>
function mergeOrderly($arr1,$arr2){ <br>
    if(!count($arr1)){//判断参数是否有意义 <br>
        return false; <br>
    }elseif(!count($arr2)){ <br>
        return false; <br>
    }else {//进行合并 <br>
        $arr = array();//定义最终数组容器 <br>
        $arr2Num = count($arr2);//统计数组长度 <br>
        $arr1Num = count($arr1); <br>
        $i1 = 0;//数组1 的循环标记 <br>
        $i2 = 0;//数组2 的循环标记 <br>
        while($i1 
            if($i1 
                if($arr1[$i1] > $arr2[$i2]){//需要比较数组1和数组2,小的放入目标数组,并且标记+1 <br>
                    $arr[] = $arr2[$i2]; <br>
                    $i2++; <br>
                }else{ <br>
                    $arr[] = $arr1[$i1]; <br>
                    $i1++; <br>
                } <br>
            }elseif($i1 = $arr2Num){//数组2 已经到达末尾,而数组1还为到达,情况二 <br>
                    $arr[] = $arr1[$i1];//直接把数组1的内容插入到目标数组中 <br>
                    $i1++; <br>
            }elseif($i2 = $arr1Num){//数组1已经到达末尾,而数组2还未到达,情况三 <br>
                    $arr[] = $arr2[$i2];//直接把数组2的内容插入到目标数组中 <br>
                    $i2++; <br>
            } <br>
        } <br>
        return $arr; <br>
    } <br>
} <br>
?> <br>
<br>
作者:dats0407						
Copy after login
Related labels:
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template