算法总结
//遍历数组 $array = array(1,3,array('adc','win32_start_service','cc',array('123')),'23',32); func($array); function func($array=array(),$level=0) { foreach ($array as $key => $value) { if(is_array($value)){ func($value,$level+1); }else{ $str = ""; for($i=0;$i<=$level;$i++){ $str .= '-'; } $str .= $value."\r\n"; echo $str; } } }
// 反转字符串
//eg 1 循环字符串从后向前输出
$str = "what is you name !";
FanZ2($str);
function FanZ($str){
$length = strlen($str);
$newstr = "";
for($i=1; $i <= $length; $i++){
$chare = substr($str,$i*-1,1);
$newstr .= $chare;
}
echo $newstr;
echo "\r\n";
}
//eg 2 更换位置第一位与最后一位,第二位与倒数第二位
function FanZ2($str)
{
$arr = str_split($str);
$len = count($arr);
$ban = floor($len/2);
for($i=0;$i<=$ban;$i++){
$tmp = $arr[$i];
$arr[$i] = $arr[$len-$i-1];
$arr[$len-$i-1] = $tmp;
}
echo implode('', $arr);
}
//算法题目:查找字符在数组中出现的次数
//eg1 循环
$array = array('a','c','dd','a','c','c','m');
findStrNums($array);
function findStrNums($array=array())
{
if(empty($array) || !is_array($array))
return false;
$only = array();
foreach ($array as $a) {
if(isset($only[$a]))
$only[$a] += 1;
else
$only[$a] = 1;
}
var_dump($only);
}
// 水仙花数
$begin = 100; $end = 10000;
NarcissisticNum($begin, $end);
function NarcissisticNum($begin=0,$end=0)
{
$begin = intval($begin);
$end = intval($end);
if($end ==0 || ($begin > $end) )
{
echo "没有可输出的!\r\n";
}
$nc = 0;
for ($i = $begin; $i < $end; $i++) {
$nc = strlen($i);
$sum = 0;
for($j = 0; $j < $nc; $j ++){
$wei = substr($i, $j, 1);
$sum += pow($wei,$nc);
}
if($sum == $i)
echo $i . "\r\n";
}
}
//折半算法
function quick_sort($array){
if(!is_array($array))
return false;
$length = count($array);
if($length <= 1)
return $array;
$base = $array[0];
$left = $right = array();
for($i=1;$i<$length;$i++){
if($array[$i] < $base){
$left[] = $array[$i];
}else{
$right[] = $array[$i];
}
}
$left = quick_sort($left);
$right = quick_sort($right);
return array_merge($left,array($base),$right);
}