0

So, this code has weird outputs when running on Command-Line with different outputs, I also get a segfault (core dumped) with some cases. I suspect it's to do with the min, max, mid bounds I have set. Please help me out as to what might be going wrong.

the code is searching based off two vectors of type class (Book) where all three elements ISBN,course, and type need to match for the counter to increment. We are searching for number of r in n.

  int binary_search(std::vector<Book> n, std::vector<Book> r){
  std::sort(n.begin(),n.end());
  unsigned int mid;
  int count  = 0 ;
  for (unsigned int i = 0; i < r.size(); i++) {
    unsigned int min = 0 ;
    unsigned int max = n.size() - 1;
    while(max >= min) {
      mid = (max + min) / (2);
      if((n[mid].isbn == r[i].isbn) &&  (n[mid].course == r[i].course) && (n[mid].type == r[i].type)) {
        count++;
        break;
      } else if(n[mid].isbn < r[i].isbn){
        min = mid + 1;
      } else{
        max = mid - 1;
      }
    }
  }
  return count;

}
  • Hi! Please provide full source code for command line functionality and example the inputs that are problematic. Thanks! – Enselic Oct 10 '19 at 03:08
  • Seems strange that `Book` would have an overload for `operator <`, but not `operator ==`. Makes me think you made a mistake in there somewhere. Also there are cases when you're trying to set max=-1, but it's `unsigned` – Matt Timmermans Oct 10 '19 at 03:15
  • https://stackoverflow.com/questions/38258457/where-is-the-mistake-in-my-code-to-perform-binary-search/38258974#38258974 – Matt Timmermans Oct 10 '19 at 03:17

0 Answers0