-1

I am trying to solve a binary search problem, however, I keep getting an infinite loop, since the values of lo hi and mid do not change as they suppose to. I am trying to search for a minimum mid value where function count_lines(mid,k) >= n. I have spent hours debugging this code but I still couldn't figure out what is wrong with the values of lo hi and mid. Could someone please look at my code and show me why this happen? Many thanks!

Failed testing case where: n=9 k=2 Here is my code:

   def count_lines(v,k):
   ...
   ...
   return count_lines #count_lines is an integer` 


   def binarySearch_v(n, k):
   lo = 0
   hi = n
   mid = (lo + hi)//2
   while (lo <= hi):
     if (count_lines(mid, k) < n):
        lo = mid
     elif (count_lines(mid, k) > n):
        hi = mid
     elif (count_lines(mid, k) >= n and count_lines(mid-1, k) < n):
        return mid
     mid = (lo + hi) // 2

    def main():
      print(binarySearch_v(n,k)) # Failed at n=9 & k=2
    main()

enter image description here

curiousP
  • 69
  • 6

1 Answers1

2

Here's your termination condition:

while (lo <= hi):

And here's where lo and hi can possibly change values:

lo = mid
...
hi = mid

The logical conclusion is that, if this code loops enough times, you'll end up with lo == hi. mid will then be set to the average of the two, which is equal to both of them, and that's where all three variables will stay. And as such, the loop will not terminate. There are two possible solutions: either change the way you're reassigning lo or hi, or change the termination condition to < instead of <=.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • Thank you for your help! I see what you are saying. I have tried to change the terminate condition from <= to < as you suggested and unfortunately I still got an infinite loop. It seems weird to me that the value of `mid` does not change even when I reassign the value of mid with new low and new high. I have attached a screenshot of my output for your view. Thanks a lot for helping! – curiousP Oct 09 '18 at 00:08
  • 1
    Seems that your code is always taking the `"GOT HERE"` branch of those if statements. I advise debugging by figuring out *why* it's always taking that branch, and what it should be doing instead. – Green Cloak Guy Oct 09 '18 at 03:10
  • I will look into that. Thanks! – curiousP Oct 09 '18 at 04:46