冒泡排序
<?php
$array = array(5, 4, 9, 20, 2, 7, 10, 17, 15 ,16 ,23);
$count = count($array);
for($i = 0; $i < $count; $i++){
for($j = $count-1; $j >= $i+1; $j--){
if($array[$j] < $array[$j-1]){
list($array[$j], $array[$j-1]) = array($array[$j-1], $array[$j]);
}
}
}
print($array);
?>
二分查找
<?php
function search($key, $array) {
$top = count($array) - 1;
$low = 0;
$mid = 0;
while ($low <= $top) {
$mid = floor(($top+$low)/2);
if($array[$mid] == $key){
return $mid;
}
if($array[$mid] > $key){
$top = $mid - 1;
}else {
$low = $mid + 1;
}
}
return false;
}
$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 888);
$position = search(70, $arr);
if($position !== false){
print('搜索元素的索引是:' . $position . "\n");
}else{
print("没有搜索到元素\n");
}
?>