Home >php教程 >php手册 >PHP冒泡法排序与二分法查找实例

PHP冒泡法排序与二分法查找实例

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-25 16:50:331271browse

冒泡法排序与二分法查找排序算法是我们在初中时就学过的,下面我来介绍在PHP冒泡法排序与二分法查 找实例,各位同学不防进入参考.

冒泡法排序,随便给出一个乱序数组

$arr = array(0,2,10,9,19,23,89,112,321,234);

统计数组:$num = count($arr);

冒泡倒序排列:

<?php
for ($i = 0; $i < $num - 1; $i++) {
    for ($m = 0; $m < $num - 1; $m++) {
        if ($arr[$m] < $arr[$m + 1]) {
            $temp = $arr[$m];
            $arr[$m] = $arr[$m + 1];
            $arr[$m + 1] = $temp;
        }
        // echo $arr[$m].&#39;<br>&#39;;
        
    }
}
//输出排序后的结果
var_dump($arr);
//冒泡顺序排列
for ($x = 0; $x < $num - 1; $x++) {
    for ($y = 0; $y < $num - 1; $y++) {
        if ($arr[$y] > $arr[$y + 1]) {
            $temp = $arr[$y];
            $arr[$y] = $arr[$y + 1];
            $arr[$y + 1] = $temp;
        }
    }
}
//输出排序后的结果
var_dump($arr);
//二分法查找
function dichotomy($array, $k, $low = 0, $high = 0) {
    if (count($array) != 0 && $high == 0) {
        $high = count($array);
    }
    if ($low <= $high) {
        $mid = intval(($low + $high) / 2);
        if ($array[$mid] == $k) {
            return $mid;
        } elseif ($k < $array[$mid]) {
            return dichotomy($array, $k, $low = 0, $mid - 1);
        } else {
            return dichotomy($array, $k, $mid + 1, $high);
        }
    } else {
        return false;
    }
}
//输出查找结果
echo dichotomy($arr, 23);
?>

今天简单的研究了一下最常用的冒泡法排序与二分法查找,写了一个简单的案例,加强自己对php的学习,也希望对今后php学习者能提供一点点的帮助。

本文地址:

转载随意,但请附上文章地址:-)

Statement:
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