排序算法:
(1)冒泡排序
$arr = array(15,8,20,50,37,85,10,5,11,4);
//冒泡排序
function maoPao($arr){
for($i = 0; $i < count($arr)-1; $i++){
for($j = 0; $j < count($arr)-1; $j++){
if($arr[$j] > $arr[$j+1]){
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
}
}
}
return $arr;
}
(2)快速排序
$arr = array(15,8,20,50,37,85,10,5,11,4);
//快速排序
function fastSort($arr){
$len = count($arr); if($len <= 1){
return $arr;
} $key = $arr[0];
$left = array();
$right = array(); for($i = 1; $i < $len; $i++){
if($arr[$i] > $key){
$right[] = $arr[$i];
} else {
$left[] = $arr[$i];
}
} $left = fastSort($left);
$right = fastSort($right); return array_merge($left, array($key), $right);
}
查找算法:
(1):普通 (适用于无规则的数组,但效率相对较低)
function search($arr, $val){
foreach($arr as $k => $v){
if($v == $val){
return $k;
}
}
return -1;
}
(2):二分查找(仅适用于有序的索引数组,效率较高)
//二分查找法
function binSearch($arr, $val){
$len = count($arr);
$low = 0;
$end = $len - 1; while($low <= $end){
$mid = floor(($low+$end)/2); if($arr[$mid] == $val){
return $mid;
} else if($arr[$mid] > $val){
$end = $mid - 1;
} else {
$low = $mid + 1;
}
} return -1;
}