tags:

views:

77

answers:

2

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

A: 

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.

Lukáš Lalinský
Thank you for the input!Yes, my professor wanted me to do a binary search that I made myself. Also, I needed to show that I could read in a file and put it into an array, which is why I read in a dictionary file.Anyway, I added the binary search that you gave me, and it worked perfectly! Much nicer than the one that I made myself. I had one problem though, which took me forever to figure out, which is the dictionary array ($dictionary) always had an extra space after each value, so I ended up having to trim every time I looked up a word in my binary search.Thanks again for the input!
James
+1  A: 

I know this doesn't directly answer your question, but have you considered using pspell and a custom dictionary?

Peter Bailey
+1 for not reinventing the wheel.
Byron Whitlock