PHP面试常见算法

//字符串的反转

$str = 'abcdefght'; function str_rev($str) { for($i=0; true; $i++) { if(!isset($str[$i])){ break; } } $newstr = ''; for($j=$i-1; $j>=0; $j--) { $newstr .= $str[$j]; } echo $newstr; } str_rev($str); echo "";

//数组的合并
function array_mer() { $newarr = []; $arr = func_get_args(); foreach ($arr as $value) { if(is_array($value)){ foreach ($value as $v) { $newarr[] = $v; } } } return $newarr; }print_r(array_mer([2],[22,33],[44,455,666])); echo "";

//猴子选大王
function king($n,$m){ $monkeys = range(1,$n); $i = 0; while (count($monkeys)>1) { if(($i+1)%$m==0){ unset($monkeys[$i]); }else{ array_push($monkeys,$monkeys[$i]); unset($monkeys[$i]); } $i++; } return current($monkeys); } echo king(10,3); echo "";

//冒泡算法
function maopao($arr){ $len = count($arr); for($k=0; $k<=$len; $k++){ for($j=$len-1; $j>$k; $j--){ if($arr[$j]<$arr[$j-1]){ $temp = $arr[$j]; $arr[$j] = $arr[$j-1]; $arr[$j-1] = $temp; }} } return $arr; } $arr = [33,1,6,5,99,75,22,24,31]; var_dump(maopao($arr)); echo "";

【PHP面试常见算法】//递归算法
function call($len){ static $i = 0; echo $i.PHP_EOL; $i++; if($i < $len){ return call($len); } } call(10);

    推荐阅读