.TITLE BinarySearch
.MCALL .PRINTS, .EXIT
; Input:
; R0 - Target value to find
; R1 - Address of the array
; R2 - Number of elements in the array
START:
MOV #TARGT, R0 ; Load the target value into R0
MOV #ARRAY, R1 ; Load the base address of the array into R1
MOV #NUMEL, R2 ; Load the number of elements into R2
JSR PC, BINSEA ; Call the binary search routine
; Check result
CMP R5, #-1 ; Was the value not found?
BEQ NOTFND ; If not found, branch
MOV #FNDMSG, R0
.PRINTS ; Print "Found!"
BR EXIT
NOTFND:
MOV #NFMSG, R0
.PRINTS ; Print "Not Found!"
BR EXIT
EXIT:
.EXIT ; Exit the program
; Binary Search Routine
; Input:
; R0 - Target value
; R1 - Array base address
; R2 - Number of elements in the array
; Output:
; R5 - Index of the target value if found, or -1 if not found
BINSEA:
MOV #0, R3 ; R3 = low index (initially 0)
DEC R2 ; Adjust R2 to be high index (N - 1)
MOV #-1, R5 ; Initialize R5 (result) to -1 (not found)
SEARLO:
CMP R3, R2 ; Compare low and high indices
BGT SEDONE ; If low > high, search is done
MOV R3, R4 ; Copy low index to R4
ADD R2, R4 ; R4 = low + high
ASR R4 ; R4 = (low + high) / 2 (mid index)
MOV R4, TMPIDX ; Use TMPIDX as a temporary index register
ADD TMPIDX, TMPIDX ; Multiply by 2 (word addressing)
ADD R1, TMPIDX ; Compute address of mid element
MOV @TMPIDX, TMPVAL ; Load value at mid element into TMPVAL
CMP TMPVAL, R0 ; Compare mid value with target
BEQ FOUND ; If equal, branch to FOUND
BLT LTTHAN ; If mid value < target, branch to LTTHAN
; If mid value > target
MOV R4, R2 ; High index = mid - 1
DEC R2
BR SEARLO
LTTHAN:
MOV R4, R3 ; Low index = mid + 1
INC R3
BR SEARLO
FOUND:
MOV R4, R5 ; Store mid index in R5 (found)
BR SEDONE
SEDONE:
RTS PC ; Return from subroutine
; Data Section
ARRAY: .WORD 1, 3, 5, 7, 9., 11., 13., 15. ; Sorted array (all decimal literals terminated)
NUMEL: .WORD 8. ; Number of elements in the array
TARGT: .WORD 7. ; Target value to find
FNDMSG:
.ASCIZ "Found!\n"
NFMSG:
.ASCIZ "Not Found!\n"
TMPIDX: .WORD 0 ; Temporary index register
TMPVAL: .WORD 0 ; Temporary value register
.END START ; Set the entry point to START