汇编语言中排序数组的二进制搜索

binary search of sorted array in assembly language

[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 分配了一个字节值,但后来在没有确定 DH 包含什么的情况下比较了 DX 中的字值。

    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 或 decrement/compare 仅使用 DL。

  • 当找不到元素时,您只需跳回标签 j2。这是错误的,因为您将使用 SI 中包含的相同数量的元素。您应该重新计算 left/right 分区中的元素数。使用 (SI / 2) 或 (SI / 2 + 1)

参考 Dirk Wolfgang Glomp 的评论

  • 看到 [org 0x100] 意味着这是一个 .COM 可执行文件,因此所有段寄存器都应该具有相同的值。那么就没有真正需要编写 DS:当使用 [bp+di] 时。

请清理您的代码

  • 连续写入 2 inc 条指令应该变成 add ..., 2
  • 在用另一个寄存器加载寄存器之前,无需在寄存器中移动零。 mov bx, 0mov bx, cx