donglin4636 2009-10-07 18:26
浏览 28
已采纳

PHP简单拼写检查(二进制搜索帮助)

I need help with performing a binary search with a search term ($searchTerm) and comparing it to a dictionary ($dictionary).

Basically, it reads a dictionary file into an array. The user inputs some words, that string becomes $checkMe. I do an explode function and it turns into $explodedCheckMe. I pass each term in $checkMe to binarySearch as $searchTerm (Okay, my code is confusing). I think my logic is sound, but my syntax isn't ...

I've been using this a lot: http://us3.php.net/manual/en/function.strcasecmp.php

here is my code: paste2.org/p/457232

  • 写回答

2条回答 默认 最新

  • dougao7801 2009-10-07 18:41
    关注

    So you are looking up exact strings in the dictionary. Why don't you a simple array for this? The native PHP's hash table is definitely going to be faster than a binary search implemented in PHP.

    while (!feof($file)) {
        $dictionary[strtolower(fgets($file))] = 1;
    }
    
    ...
    
    function search($searchTerm, $dictionary) {
        if ($dictionary[strtolower($searchTerm)]) {
            // do something
        }
    }
    

    But if you really want to use a binary search, try this:

    function binarySearch($searchTerm, $dictionary) {
        $minVal = 0;
        $maxVal = count($dictionary);
        while ($minVal < $maxVal) {
            $guess = intval($minVal + ($maxVal - $minVal) / 2);
            $result = strcasecmp($dictionary[$guess], $searchTerm);
            if ($result == 0) {
                echo "FOUND";
                return;
            }
            elseif ($result < 0) {
                $minVal = $guess + 1;
            }
            else {
                $maxVal = $guess;
            }
        }
    }
    

    The main problem was that you can't set $maxval to $guess - 1. See the wikipedia article on binary search, it's really good.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?