PHP三种算法

// 二分法  $arr 数组,$k 要查找的值,$m 最小,$b最大
function dichotomy($arr, $k, $m = 0, $b = 0) {
	$total = count($arr);
	if ($total != 0 && $b == 0) $b = $total;
	if ($m <= $b) {
		$avg = intval(($m + $b) / 2);
		if ($arr[$avg] == $k) return $avg;
		elseif ($k < $arr[$avg]) return dichotomy($arr, $k, $m, $avg-1);
		else return dichotomy($arr, $k, $avg + 1, $b);
	}
	return false;
}
echo "<hr>二分法查找<br>";
$arr = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
var_dump(dichotomy($arr, 1));
// 冒泡排序
function bubblesort($arr) {
	$total = count($arr);
	for($i = 0;$i < $total-1;$i++) {
		for($l = $i + 1;$l < $total;$l++) {
			if ($arr[$i] > $arr[$l]) {
				list($arr[$l], $arr[$i]) = array($arr[$i], $arr[$l]);
			}
		}
	}
	return $arr;
}
echo "<hr>冒泡排序<br>";
$arr = array(1, 100, 23, 434, 22, 12, 3, 5);
var_dump(bubblesort($arr));
// 从字符串中搜索子串 $text 字符串,$str 要搜索的子串
function search($text, $str) {
	$strLen = strlen($str);
	$textLen = strlen($text);
	for($i = 0;$i < $textLen - $strLen;$i++) {
		if (substr($text, $i, $strLen) == $str) return $i;
	}
	return false;
}
echo "<hr>字符串中搜索子串<br>";
$text = "pdsofuapdoi3409729fhydish";
var_dump(search($text, "7"));

你可能感兴趣的:(php函数,php算法,php字符串查找,php冒泡排序法,php二分法)