快速排序、二分法查找的PHP实现代码

时间:2022-10-27 18:15:28

快速排序PHP排序代码

//快速排序
function quickSort($array){
$length = count($array);
if($length < 1){

return $array;
}
$left = $right = array();
$base = $array[0];
for($i = 1;$i < $length;$i++){

if($array[$i] < $base){
$left[] = $array[$i];
}else{
$right[] = $array[$i];
}
}

$left = quickSort($left);

$right = quickSort($right);

return array_merge($left,array($base),$right);

}
$test_array = array(19,54,3,4,1,76,10,32);
print_r(quickSort($test_array));



/*二分法查找的PHP实现代码

 * @param $array为有序数组
 * @param $target为目标值
 * return 目标值索引
 */ 
function binarySearch($array,$target){


$low = 0;
$high = count($array)-1;

while($low <= $high){
$mid = intval(($low + $high)/2);

if($array[$mid] == $target){

return $mid; //Done!找到目标值,返回其索引
}else if($array[$mid] < $target){

$low = $mid + 1; //目标值在右边  
}else{

$high = $mid -1; //目标值在左边
}
}
 
}


$test_array = array(1,3,4,10,32,45,63,81,93,106,309);
echo binarySearch($test_array,106);





今天发现一个在线调试代码的地址,分享给大家http://tool.lu/