二进制搜索排序阵列在汇编语言
[org 0x100]
;This code is for counting the size
mov di, 0 ; to be used for indexing
mov bp, s_a
mov cx, 0
jmp count
j1: inc cx ; storing the size in cx
count: mov ax, [bp+di]
add di, 2
cmp ax, -1 ;-1 is the ending condition
jne j1
;=================================;
mov si, cx ;Moving the size in si
mov cx, 2 ;using cx for division number
;This code is for finding the centre point by division
j2: mov ax, si
mov bx, 0
mov bx, cx
div bl
;=================================;
inc cx
inc cx
cmp al, 0 ;If al has 0 then the number is not in array
je nfound
mov dl, al
mov di, 0
;Increasing bx to point to the required number
j3: inc di
inc di
dec dx
cmp dx, 0
jne j3
;=================================;
mov ax, [bp+di] ;Moving the centre number in array to ax
mov dx, [b_s] ;The number to be found
cmp dx, ax
je found
cmp dx, ax
jl below
cmp dx, ax
jg above
above: add bp, di
jmp j2
below: jmp j2
found: mov cx, bp
add cx, di
jmp exit
nfound: mov ax, [bp] ;This code is for the first element
mov di, 0
cmp ax, [b_s]
je found
;=================;
mov cx, 0xffff
exit:
mov ax, 4c00h
int 21h
s_a: dw 1, 2, 3, 4, 5, -1
b_s: dw 5
这是我的代码二进制搜索其工作罚款的所有数字在这里除了'1'和'5'。我已经处理了'1'。请建议'5'的解决方案。这意味着最后的号码。 '-1'不被搜索。二进制搜索排序阵列在汇编语言
我看到了你的代码可能失败的一些原因。
-
您为DL分配一个字节值,但稍后比较DX中的字值而不确定DH包含的值。
mov dl, al mov di, 0 ;Increasing bx to point to the required number j3: inc di inc di dec dx cmp dx, 0 jne j3
明确地清除DH或仅与DL进行递减/比较。
当元素未找到时,您只需跳回标签j2。这是错误的,因为您将使用SI中包含的相同数量的元素。您应该重新计算左/右分区中的元素数量。既可以使用(SI/2)或(SI/2 + 1)
参照由德克沃尔夫冈Glomp
- 眼看
[org 0x100]
将意味着这是一个.COM可执行文件和这样所有的评论段寄存器应该具有相同的值。那么没有必要编写DS:使用[bp+di]
时。
请清理你的代码
- 写在一排2
inc
说明应成为add ..., 2
- 没有必要在寄存器与另一寄存器加载之前移动为零。
mov bx, 0
mov bx, cx
当调试器开始它的值时,关于dx已经是0,但我按照你的说法清除它。但仍然是同样的事情。关于si,如果我在j1上跳跃,那么它的工作原理是一样的吗? –
只需将'jmp j2'改成'jmp j1'即可解决问题。作为标签的例子:_你需要以下内容:'shr si,1''mov cx,2''jmp j2' – Fifoernik
使用“bp”作为地址寄存器的默认段是堆栈段,但不是数据段。为了修复代码,您可以额外使用DS段覆盖前缀。例如:mov ax,DS:[bp + di] –
为什么在等效的“shr 1”中使用非常昂贵的指令“div”? –
当您的代码跳回到* j2 *标签时,它使用的CX值太高,无法找到中心点*。总是除以2,或者右移一次。 –