首页 > 解决方案 > cmp 指令不在 InsertionSort 中进行 jge 跳转

问题描述

我正在尝试使用 MASM 编写 InsertionSort 的迭代版本。在反复出现意外错误后,我尝试逐行运行代码并在调试器中观察它是否符合我的预期。果然,我的'while循环'中的 cmp 指令似乎并没有在每次它应该跳跃时都跳跃:

; store tmp in edx
    movzx edx, word ptr[ebx + esi * 2];   edx: tmp = A[i]
    ...
    //blah blah

while_loop :
...
    movzx eax, word ptr[ebx + 2 * edi]
    cmp dx, ax
    jge exit_while

例如,如果我使用给定的数据,在第一次“for 循环”迭代之后,我会到达 EDX=0000ABAB 和 EAX=00003333 的点。我达到了以下要求:

cmp dx, ax
jge exit_while

由于 ABAB>3333,我希望它跳转到 exit_while,但它没有!

这里发生了什么???我完全不知所措。

.data
arr word 3333h, 1111h, 0ABABh, 1999h, 25Abh, 8649h, 0DEh, 99h
sizeArr dword lengthof arr
printmsg byte "The array is: [ ", 0
comma byte ", ", 0
endmsg byte " ]", 0

.code
main proc
    call printArr
    call crlf
    push sizeArr
    push offset arr
    call insertionsort
    call crlf
    call printArr
    call crlf
    call exitprocess
main endp


insertionsort proc
    push ebp
    mov ebp, esp
    _arr = 8
    len = _arr + 4

    mov ebx, [ebp + _arr]
    mov ecx, [ebp + len]
    dec ecx
    mov esi, 1; store i in esi, with i=1 initially

;   for (i = 1; i < SIZE; i++)
forloop:

; store tmp in edx
    movzx edx, word ptr[ebx + esi * 2];   edx: tmp = A[i]

; store j in edi, where in initially j = i
    mov edi, esi
;set j=i-1
    dec edi

;while (j >= 0 &&   tmp<arr[j])
while_loop :
    cmp edi, 0
    jl exit_while
    movzx eax, word ptr[ebx + 2 * edi]
; cmp dx, [ebx + 2 * edi]
    cmp dx, ax
    jge exit_while

; A[j] = A[j-1]
    push word ptr [ebx+2*edi]
    pop word ptr [ebx+2*edi+2]
; j = j - 1
    dec edi
    jmp while_loop

exit_while:
    push dx
    pop word ptr[ebx + 2*edi+2]
    ; mov[ebx + edi], dx;    A[j] = tmp
    inc esi;     i = i + 1
    loop forloop

finished:
    mov esp, ebp
    pop ebp
    ret 8
insertionsort endp



printArr proc
    push ebp
    mov ebp, esp
    mov ebx, offset sizeArr
    mov ecx, [ebx]
    mov esi, offset arr
    mov edx, offset printmsg
    call writestring
    mov edx, offset comma
loop1 :
    movzx eax, word ptr [esi]
    call writeHex
    call writestring
    add esi, 2
loop loop1

    mov edx, offset endmsg
    call writestring
    mov esp, ebp
    pop ebp
    ret
printArr endp

标签: arrayssortingassemblyx86masm

解决方案


jge是有符号值的版本 - 因此,值为ABAB负的单词 - 因此您看到的比较结果。

尝试jae(如果高于或等于则跳转) - 无符号等价物。


推荐阅读