Search code examples
assemblyirvine32

Unable to find negative numbers for Longest Decreasing Sequence


I wrote an assembly code combined with C. It only works if the numbers in the array are positive numbers. If I want to test any negative numbers, it skips the numbers.

Here is my assembly code:

INCLUDE Irvine32.inc

.data

; LSD
bestIndex dword 0
bestLen dword 0
curIndex dword 0
curLen dword 1
i dword 1
strLSD byte "Longest Decreasing Sequence: ", 0
strBestIndex byte "Begins at index ", 0
strBestLen byte " and has a length of ", 0

.code

findLDS proc C arr:sdword, len:dword
;arr - array passed from C
;len is the length of the array

mov ecx, len
mov esi, arr
add esi, type arr

compare:
    .IF i <= ecx
    jmp cont
    .ELSE
    jmp ex
    .ENDIF

cont:
    mov eax, dword ptr [esi - type arr]
    .IF dword ptr [esi] <= eax
    jmp incCurLen
    .ELSE
    jmp setCurLen
    .ENDIF

incCurLen:
    inc curLen
    jmp compareCurLen

setCurLen:
    mov curLen, 1
    mov eax, i
    mov curIndex, eax
    jmp compareCurLen

compareCurLen:
    mov eax, bestLen
    .IF curLen > eax
    jmp changeBest
    .ELSE
    jmp incI
    .ENDIF

changeBest:
    mov eax, curIndex
    mov bestIndex, eax
    mov eax, curLen
    mov bestLen, eax
    jmp incI

incI:
    inc i
    add esi, type arr
    jmp compare

ex:
    ; when our loop ends, print the sequence
    mov ecx, bestLen
    mov ebx, bestIndex
    mov edx, offset strLSD
    call writestring

    L1:
        push ecx
        mov esi, arr
        mov eax, dword ptr [esi + type arr*ebx]
        call writeint
        mov al, ','
        call writechar
        mov al, ' '
        call writechar
        inc ebx
        pop ecx
        loop l1

call crlf
mov edx, offset strBestIndex
call writestring
mov eax, bestIndex
call writedec

mov edx, offset strBestLen
call writeString
mov eax, bestLen
call writedec

call crlf
ret
findLDS endp

END

Here is my C code:

int main()
{

int arr[] = { -5, 10, 20, 80, 73, 32, 20, 22, 19, -5 };
int len = (sizeof(arr) / sizeof(*arr));
findLDS(arr, len);

return 0;
}

Output for this array:

Longest Decreasing Sequence: +80, +73, +32, +20. Begins at index 3 and has a length of 4

Which is correct, but if I change my array's 20 (index 6) to -20, my output is

Longest Decreasing Sequence: +80, +73, +32. Begins at index 3 and has a length of 3


Solution

  • As suggested by @Jester, I changed it to signed cmp and it works.

    Code:

    cont:
        mov eax, dword ptr [esi - type arr]
        cmp dword ptr [esi], eax
        jle incCurLen
        jmp setCurLen