Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++ Question, Binary Searching!?

here is my code, i am trying to binary search a vector to see if it is finding the right stuff.

i am using std::sort in main, so it is sorted

here is my code: it is currently throwing a segfault or not running at all.. but it compiles fine

//boolean to test incoming words if they are, indeed a stop_word

bool isStopWord(string word, vector<string> &STOP_WORDS){

//sort( STOP_WORDS.begin(), STOP_WORDS.end() );

//boolean for return

bool retbool = false;

//binary search this badboy

int low = 0;

int high = STOP_WORDS.size();

while(low<=high){

int middle = low + ((high-low)/2);

if(word < STOP_WORDS[middle]){

high = middle-1;

}

else if(STOP_WORDS[middle] < word){

low=middle+1;

}

else{

retbool = true;

}

}

return retbool;

}

1 Answer

Relevance
  • 10 years ago
    Favorite Answer

    The only potential segfault I see is in setting high to STOP_WORDS.size() instead of size()-1. That will cause a compare to a nonexistent array beyond the end, if the search key is higher than any actual key in the table.

Still have questions? Get your answers by asking now.