I’m using Schaum’s Outline of Programming With Fortran 77 book, and there’s an example about binary search using bracketing group of values method. First of all here’s the code :
INTEGER X(100)
INTEGER RANGE
INTEGER START , FINISH
PRINT *, 'Number of values ?'
READ *, N
DO 10 I = 1, N
READ *, X(I)
END DO
PRINT *, 'Enter Value'
READ *, VAL
START = 1
FINISH = N
RANGE = FINISH - START
MID = (START + FINISH) /2
DO WHILE( X(MID) .NE. VAL .AND. RANGE .NE. 0)
IF (VAL .GT. X(MID))THEN
START = MID
ELSE
FINISH = MID
END IF
RANGE = FINISH - START
MID = (START + FINISH)/2
END DO
IF( X(MID) .NE. VAL) THEN
PRINT *, VAL, 'NOT FOUND'
ELSE
PRINT *, 'VALUE AT' , MID
END IF
END
The problem is, when i enter 7 values array like
2 | 9 | 11 | 23 | 49 | 55 | 66
And search for 66 for example, when
MID = 5
, the new MID for the next loop becomes 6 . But when it’s 6, it can’t get incremented for the next loop because
MID = (START + FINISH)/2 = (6+7)/2 = 6
Where it should be 7 of course.
It still on 6. And my program never give me an output of course.
What shall I do here ?
This is just a typo, or maybe someone got confused when they translated it from a C version and had to to change indexing.
The key invariant in the loop is that the value, if it’s in the list, must fall in the array somewhere from indices start to finish, inclusive. But once you’ve excluded mid, it should be taken out the list. But it’s not here, so the list is always too long and you run into the problem you see.
A correct version sets start to mid+1, or finish to mid-1, to exclude mid. The corrected code, written in a Fortran 90 style: