可复制版
;堆栈段
sseg SEGMENT stack
dw 32 DUP(?)
sseg ENDS
;数据段
dseg SEGMENT
buf db 3,2,1,4,5,9,8,6,7
N=$-buf
num db 9
mes db 'not found$'
lowN db ?
midN db ?
hiN db ?
dseg ENDS
;代码段
cseg SEGMENT
assume cs:cseg,ds:dseg,ss:sseg
start:
mov ax,dseg
mov ds,ax
;寄存器传递参数
lea di,buf
mov cx,N
call sort ;调用排序
;显示
show: mov dl,[di]
add dl,30h
mov ah,02h
int 21h
inc di
loop show
lea di,buf
mov cx,N
;回车换行
mov dl,0dh
mov ah,02h
int 21h
mov dl,0ah
mov ah,02h
int 21h
call sreach ;调用查找
;程序结束
mov ah,4ch
int 21h
;排序子程序
sort PROC
push cx
push di
dec cx
rond:
push cx
mov si,di
cont:
mov al,[si]
cmp al,[si+1]
jbe next
xchg al,[si+1]
mov [si],al
next:
inc si
loop cont ;内循环
pop cx
loop rond ;外循环
;恢复现场
pop di
pop cx
ret
sort ENDP
;2分查找
sreach PROC
;保护现场
push cx
push di
;准备工作
dec cl
mov ax,0
mov lowN,al
mov midN,al
mov hiN,cl
mov si,di
xor ax,ax
mov bl,2
cont1: ;第一次执行和当前数大于查找数时
cmp midN,0
jz tmp
inc al
tmp:
mov lowN,al
jmp next2
cont2:
mov al,midN
mov hiN,al
next2:
mov al,lowN
add al,hiN ;low+high
mov dx,0
div bl ;mid=(low+high)/2
mov midN,al ;将存入mid
mov ah,0
add si,ax ;取数
mov bh,[si]
mov si,di
cmp bh,num
jz find ;如果等于则输出结果否则判断是否还可以比较
mov dh,lowN
cmp dh,hiN
jz notfound
cmp bh,num
jb cont1 ;如果小于跳转cont1
cmp bh,num
ja cont2 ;如果大于跳转cont2
notfound:
lea dx,mes
mov ah,09h
int 21h
jmp over
find:
mov dl,midN
add dl,30h
mov ah,02h
int 21h
over:
;回车换行
mov dl,0dh
mov ah,02h
int 21h
mov dl,0ah
mov ah,02h
int 21h
;恢复现场
pop di
pop cx
ret
sreach ENDP
cseg ENDS
end start