Download Print this page

ZiLOG Z80 Handbook page 194

Hide thumbs Also See for Z80:

Advertisement

given entry in 11 iterations or less [N (1092 1000) + 1 = 9.XX + 1
= 11], whereas a sequential search will take an average of 500 ac-
cesses.
The following routine performs a binary search for an 8-bit value
for a table of 256 entries, or less, that starts at TABLE and ends at
TABEND. Each entry has one byte, the search key itself, as shown
in Fig. 13-6.
BINSRC LD B,0 SET LOW INDEX = 0
LD C,TABEND-TABLE SET HIGH INDEX = LAST
LD D,0 INITIALIZE DE
LD E,C INITIALIZE LAST INDEX
LD IX,KEY POINT TO KEY
JP JUMPI FIRST TEST = LAST ENTRY
LOOP LD A,C
SUB A,B HIGH-LOW
SRL A (HIGH-LOW)/2
LD E,A MIDPOINT DISPLACEMENT
JUMP1 LD HL,TABLE TABLE START
ADD HL,DE START + (HIGH-LOW/2)
L,D A, L
ADD A,B LOW + (HIGH-LOW/2)
LDD L,A
JP NC,JUMP2 GO IF NO CARRY TO MSB
INC H BUMP MSB
JUMP2 LD A,(HL) GET ENTRY
CP (IX) COMPARE WITH KEY
JP Z,FOUND GO IF MATCH
JP M,JUMP3 GO IF ENTRY LT KEY
LD B,E CURRENT TO LOW
JP LOOP CONTINUE
JUMP3 LD C,E CURRENT TO HIGH
JP LOOP CONTINUE
The routine, first of all, compares the last entry of the table with
the search key (to avoid truncation errors in computing the next in-
dex). If the key is not found, the iterative portion of the routine is
entered. For each iteration, new low and high limits are established
based on the results of the last comparison. The current index in E
is put into either C (high) or B (low) as the new limit. The mid-
point displacement of the area to be searched is then computed
(HIGH - LOW)/ 2, and added to the address of low to find the
next location for the search. The value in the next location is then
compared with the search key and if unequal, the next binary search
area and location are computed. In the above loop, there is no check
on terminating conditions for the search. If the key exists, as we have
assumed, it will eventually be found and the instruction at FOUND
will be executed. If the key does not exist, no termination of the loop
203

Advertisement

loading
Need help?

Need help?

Do you have a question about the Z80 and is the answer not in the manual?

Questions and answers