Sunday, August 2, 2009

C++, Binary Searching a string?

Could someone please tell me what is wrong wit this? I basically want to be able to preform a binary search on a string but I'm not quite sure how to do it. If you could please show me how to do it that would be great. The code can be found at http://cpp.sourceforge.net/?show=35467





I have posted it up so it doesn't need to be downloaded or anything.

C++, Binary Searching a string?
C-style strings cannot be compared using == or %26gt; or %26lt; operators, you need to use the strcmp function. Here is a fix to your search function:


Code:





int binarySearch( char array[][SIZE], int numelems, char value[SIZE]) { int first = 0, last = numelems - 1, middle, position = -1; bool found = false; while (!found %26amp;%26amp; first %26lt;= last) { middle = (first + last) / 2; if (!strcmp(array[middle], value)) { found = true; position = middle; } else if (strcmp(array[middle], value)%26gt;0) last = middle - 1; else first = middle + 1; } return position; }





If you used std::string instead of C-style strings, those operators would have had worked well. std::string has those operators overloaded to work as you expect.
Reply:Nice work. You're abusing SF resources for your own webspace. I was wondering about that project, and it turns out you're the admin. Nice...

crab apple

No comments:

Post a Comment