Chris wrote a binary search program that returns the index of the number in list , if not found.
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Weird enough, when he runs
search(6,L)
on the list
L = [1,2,3,4,5,6,7,8]
the code returns
-1
instead of
5
. Which is
the only
line Chris should edit to correct the code?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
In terms of definition of search range, there are two types of implementation for the Binary Search algorithm.
Type 1 : ( l , r ) implies the range [ l , r ] = { l , l + 1 , … , r − 2 , r − 1 , r }
Applying this definition, line 3 is wrong because
L[hi]
does not exist. Line 4 is also incorrect because it terminates whenlo == hi
but in this case the search space is not empty. We have to change 2 lines to make this implementation work.Type 2 : ( l , r ) implies the range [ l , r ) = { l , l + 1 , … , r − 2 , r − 1 }
Using this definition,
hi
is one right to the rightmost possible number. Line 3 makes sense asL[len(L)-1]
is the rightmost number. Line 4 is also true because whenlo == hi
this implies that the search space is empty. The only line that contains error is in line 1 1 which happens whenL[mid] > x
. In this case,mid-1
is still a possible number to be x but notmid
. Hence,hi
should bemid
instead ofmid-1
.