首页 > php数组 > 冒泡排序与数组交集php做法

冒泡排序与数组交集php做法

冒泡排序-php版本-交换排序法

<?php
$a=array('11','2','13','4','22'); 
$num = count($a);
for ($i = 0; $i < $num; $i++) {
    for ($j = 0; $j < $num; $j++) {
        if ($a[$i] < $a[$j]) {
            $temp = $a[$i];
            $a[$i] = $a[$j];
            $a[$j] = $temp;
        }
    }
}
print_r($a);
?>

归并排序-数组交集-php版

<?php
$a=array('1','2','3','4','22');
$b=array('1','3','4','11','22','23');
f($a, $b, 5, 6, $t);
print_r($t);
function f(&$a, &$b, $n, $m, &$t) {
    $i = 0;
    $j = 0;
    while ($i < $n && $j < $m) {
        if ($a[$i] == $b[$j]) {
            echo $a[$i] . " "; //交集
            $t[] = $a[$i++];
            $t[] = $b[$j++];
        } elseif ($a[$i] > $b[$j]) {
            $t[] = $b[$j++];
        } else {
            $t[] = $a[$i++];
        }
    }
    while ($i < $n) {
        $t[] = $a[$i++];
    }
    while ($j < $m) {
        $t[] = $b[$j++];
    }
}
?>

               
               

永久地址:http://www.phprm.com/shuzu/fs1341.html

转载随意~请带上教程地址吧^^

标签:排序 数组 冒泡

相关文章

发表留言