二分查詢【折半查詢】演算法 PHP 版

勺顛顛發表於2019-07-30

查詢表:就是同一型別的資料元素構成的資料集合
有靜態表和動態表
本文實現PHP版的二分查詢演算法【本演算法僅用於順序儲存的查詢表】

<?php
/**
 * Created by PhpStorm.
 * User: 1655664358@qq.com
 * Date: 2019/7/01
 * Time: 11:38
 */

class Elem{
    public $key;
}

class Table
{
    public $data = [];
    public $lenght;
}
function createTable(Table &$table,$length)
{
    $table->lenght = $length;
    $obj = new Elem();
    fwrite(STDOUT,"請輸入資料:\n");
    for($i=1;$i<=$table->lenght;$i++){
        $elem = clone $obj;
        $elem->key = fgets(STDIN,10);
        $table->data[$i] = $elem;
    }
}

function searchBin(Table $table,$key):int
{
    $low = 1;
    $height = $table->lenght;
    while($low<=$height){
        $mid = floor(($low+intval($height))/2);
        if ($table->data[$mid]->key==$key){
            return $mid;
        }else if($table->data[$mid]->key>$key){
            $height=$mid-1;
        }else{
            $low = $mid+1;
        }
    }
    return 0;
}
(function(){
    $table = new Table();
    fwrite(STDOUT,"請輸入資料元素個數:\n");
    $length = fgets(STDIN,10);
    createTable($table,$length);
    fwrite(STDOUT,"請輸入要查詢的資料元素:\n");
    $key = (integer)fgets(STDIN,10);
    $location = searchBin($table,$key);
    if ($location){
        fwrite(STDOUT,"查詢到的資料索引為:$location\n");
    }else{
        fwrite(STDERR,"查詢不到指定的內容\n");
    }
})();

相關文章