Skip to content

Instantly share code, notes, and snippets.

@Subangkar
Last active May 20, 2022 03:25
Show Gist options
  • Save Subangkar/182fe88d3b34d814a68ac98d375e6492 to your computer and use it in GitHub Desktop.
Save Subangkar/182fe88d3b34d814a68ac98d375e6492 to your computer and use it in GitHub Desktop.
8086-Assembly-Language Procedure for Binary Search
BIN_SEARCH PROC
;search in a sorted array by the binary search method
;input: SI = array offset address
; BX = number of elements
; CX = key
;output: SI = offset of sorted array
; AX = pos @where key has been found
;PUSH AX
PUSH BX
PUSH CX
PUSH DX
PUSH SI
PUSH DI
MOV DX,BX ; DX = rIndex
DEC DX
MOV BX,0 ; BX = lIndex
@START_BIN_SEARCH: ; BX=l,AX=m,DX=r
CMP BX,DX ; exit when lIndex > rIndex
JG @NOT_FOUND_BIN_SEARCH
MOV AX,BX
ADD AX,DX ; AX=BX+DX
SHR AX,1 ; AX = midIndex ; m=(l+r)/2
;MOV SI,AX
;ADD SI,SI
MOV DI,SI
ADD DI,AX
ADD DI,AX
CMP CX,[DI]
JE @FOUND_BIN_SEARCH
JG @BIG_PIVOT_BIN_SEARCH
JMP @SMALL_PIVOT_BIN_SEARCH
@BIG_PIVOT_BIN_SEARCH:
INC AX
MOV BX,AX ; l=m+1
JMP @START_BIN_SEARCH
@SMALL_PIVOT_BIN_SEARCH:
DEC AX
MOV DX,AX ; r=m-1
JMP @START_BIN_SEARCH
@NOT_FOUND_BIN_SEARCH:
MOV AX,-1
JMP @END_BIN_SEARCH
@FOUND_BIN_SEARCH: ; index already in AX
;ADD AL,01
JMP @END_BIN_SEARCH
@END_BIN_SEARCH:
POP DI
POP SI
POP DX
POP CX
POP BX
;POP AX
RET
BIN_SEARCH ENDP
@sfoduntan
Copy link

How do you write this function for 32-bit array?

@Subangkar
Copy link
Author

As each REG is 16-bit hence you will have to use nested comparison of two REG. For example, you'll have to move upper 16-bit into one REG and lower one into another. Then compare upper first and if equal then lower to decide next index. You'll have to increase offset index considering 32-bit.

@sushil-2803
Copy link

how can i run this program i am new to this please help

@Subangkar
Copy link
Author

how can i run this program i am new to this please help
@sushil-2803
You will find the whole project here Binary-Search-8086-assembly.

@PS1607
Copy link

PS1607 commented Oct 20, 2021

Do you have the flowchart for this?

@Subangkar
Copy link
Author

Do you have the flowchart for this?

There isn't any documented flowchart. But you will get the intuition from the whole project here Binary-Search-8086-assembly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment