php常见算法
- 2分查找
- 快速排序
- 选择排序
- 归并排序
1,二分查找做多需要log2n步;--对数是幂运算的逆运算。
<?php ini_set('error_reporting', E_ALL); ini_set('display_errors', 'on'); function binary_search($a ,$b = 0) { $low = 0; $hign = count($a) -1; while ($hign >= $low) { $mid = floor(($low + $hign)/2); if ($a[$mid] == $b) { return $a[$mid]; } elseif ($a[$mid] > $b) { $hign = $mid - 1; } elseif($a[$mid] < $b) { $low = $mid + 1; } } return '没有相关字符'; } $a = [1,2,33,47,555,666,888]; $b =34; echo binary_search($a,$b);
<?php //快速排序 $arr = [5,8,324,54,56,1,2,3]; function quick_sort($arr){ $len = count($arr); if ($len <= 1) return $arr; $r = $l = []; for($i = 1;$i<$len ;$i++){ if($arr[$i] > $arr[0]){ $r[] = $arr[$i]; } else { $l[] = $arr[$i]; } } $r = quick_sort($r); $l = quick_sort($l); return array_merge($l , [$arr[0]], $r); } print_r(quick_sort($arr));
选择排序 <?php $arr = [5,8,324,54,56,1,2,3]; $len = count($arr); for($i=0 ;$i<$len ;$i++){ $min = $i; for($j = $i+1;$j<$len ;$j++){ if($arr[$j] < $arr[$min]){ $min = $j; } } if ($min != $i){ $tem = $arr[$i]; $arr[$i] = $arr[$min]; $arr[$min] = $tem; } } print_r($arr);
<?php //归并排序 $arr = [5,8,324,54,56,1,2,3]; function m_sort($arr){ $len = count($arr); if ($len <= 1) return $arr; $mid = floor($len/2); $left = array_slice($arr , 0 , $mid); $right = array_slice($arr,$mid); $left = m_sort($left); $right = m_sort($right); $m = []; while(count($left)>0 && count($right) >0){ $m[] = $left[0] < $right[0] ? array_shift($left) : array_shift($right); } return array_merge($m, $left, $right); } print_r(m_sort($arr));