PHP排序算法

作者: admin 分类: PHP 发布时间: 2017-07-22 18:56

1.归并排序

$a = [1, 4, 6, 8, 10, 14, 16];
$b = [2, 3, 5, 8, 9, 11];
function merge_sort($a, $b)
{
    $a_i = $b_i = 0;
    $count_a = count($a);
    $count_b = count($b);
    $ret = [];
    while ($a_i < $count_a && $b_i < $count_b) {
        if ($a[$a_i] > $b[$b_i]) {
            array_push($ret, $b[$b_i]);
            $b_i++;
        } else {
            array_push($ret, $a[$a_i]);
            $a_i++;
        }
    }
    if ($a_i < $count_a) {
        $ret = array_merge($ret, array_slice($a, $a_i));
    }
    if ($b_i < $count_b) {
        $ret = array_merge($ret, array_slice($b, $b_i));
    }
    return $ret;
}

$ret = merge_sort($a, $b);
echo implode(',', $ret);

2.选择排序

$arr = [1, 5, 2, 7, 97, 23, 1, 4];
function select_sort(array $arr)
{
    $count = count($arr);
    if ($count < 2) return $arr;
    for ($i = 0; $i < $count; $i++) {
        $min = $arr[$i];
        $min_i = $i;
        for ($j = $i; $j < $count; $j++) {
            if ($arr[$j] < $min) {
                $min = $arr[$j];
                $min_i = $j;
            }
        }
        $arr[$min_i] = $arr[$i];
        $arr[$i] = $min;
    }
    return $arr;
}

$ret = select_sort($arr);
echo implode(',', $ret);
 

3.插入排序

$arr = [1, 5, 2, 7, 97, 23, 1, 4];
function insert_sort($arr)
{
    $count = count($arr);
    if ($count < 2) return $arr;
    for ($i = 0; $i < $count; $i++) {
        for ($j = $i; $j > 0; $j--) {
            if ($arr[$j] < $arr[$j - 1]) {
                $tmp = $arr[$j - 1];
                $arr[$j - 1] = $arr[$j];
                $arr[$j] = $tmp;
            }
        }
    }
    return $arr;
}

$ret = insert_sort($arr);
echo implode(',', $ret);

4.冒泡排序

$arr = [1, 5, 2, 7, 97, 23, 1, 4];
function maopao_sort($arr)
{
    $count = count($arr);
    if ($count < 2) return $arr;
    for ($i = 0; $i < $count; $i++) {
        for ($j = 0; $j < $count - $i - 1; $j++) { // 注意$j的上限,小心数组越界
            if ($arr[$j] > $arr[$j + 1]) {
                $tmp = $arr[$j + 1];
                $arr[$j + 1] = $arr[$j];
                $arr[$j] = $tmp;
            }
        }
    }
    return $arr;
}

$ret = maopao_sort($arr);
echo implode(',', $ret);

发表评论

电子邮件地址不会被公开。 必填项已用*标注