After reading Sam Davis's algorithm on Binary Search which reads
If I had 5 Items and the item I was trying to find was number 4 in the list...
After First Part the Low would be Middle + 1 Therefore Number 4
2nd Pass would involved middle being [(4 + 5)/2] which would be 4.5 so rounded to 5 I presume?
This is when I get confused since the target item is smaller then the middle it would make High to Middle - 1 (Thus 4)
But then both High and Low would equal 4 and the number would not actually be found
Can someone please clear the confusion
Thanks
ps. sorry about the >>> I dunno how to indent
Code:
BEGIN BinarySearch
Set Low to 1
Set High to number of items in list
Set Found to False
Get ItemToFind
WHILE High > Low AND Found = False
Set Middle to INT((Low + High)/2)
IF ItemToFind < Item(Middle) THEN
Set High to Middle - 1
ELSEIF ItemToFind = Item(Middle) THEN
Set Found to True
ELSE
Set Low to Middle + 1
ENDIF
ENDWHILE
IF Found = True THEN
Display "Found"
ELSE
Display "Not Found"
ENDIF
END BinarySearch
After First Part the Low would be Middle + 1 Therefore Number 4
2nd Pass would involved middle being [(4 + 5)/2] which would be 4.5 so rounded to 5 I presume?
This is when I get confused since the target item is smaller then the middle it would make High to Middle - 1 (Thus 4)
But then both High and Low would equal 4 and the number would not actually be found
Can someone please clear the confusion
Thanks
ps. sorry about the >>> I dunno how to indent
Last edited by a moderator: