PHP二分查找和快速排序

二分查找

function bin_search ($arr, $num)
    {   

        if (!in_array($num, $arr)) {
            return 'error num input';
        }

        $len = count($arr);
        $start = 0;
        $end = $len-1;


        while ($start <= $end) {

            $mid = ceil( ($end+$start)/2 );

            if ($arr[$mid] < $num) {
                $start = $mid + 1;
            }elseif ($arr[$mid] > $num) {
                $end = $mid - 1;
            }else {
                return $mid;
            }   
        }
        return false;
    }

$arr = [1,2,3,4,5,6];
echo bin_search($arr, 1);

由于二分查找需要的是有序数组,所以顺便贴一个 快速排序法
快速排序

function quickSort( array $arr) {
    if (!isset($arr[1])) {
        return $arr;
    }

    $left = $right = $midium = [];
    $rand = $arr[0];
    foreach ($arr as $v) {
        if ($rand < $v) {
            $right[] = $v;
        }
        if ($rand > $v) {
            $left[] = $v;
        }
//此步为了处理重复值
        if ($rand == $v) {
            $midium[] = $v;
        }
        
    }
    
    $left = quickSort($left);
    $right = quickSort($right);
    return array_merge($left, $midium, $right);
        
}

$arr2 = [2,0,54,2342,56,22,5];
var_dump(quickSort($arr2));

你可能感兴趣的:(PHP二分查找和快速排序)