Bubble Sort using Assembly x86-64 for Linux and display on screen the sorted vector

Viewed 32

I created this code to sort an array with n positions using NASM x86-64 on Linux but I can't see the value ​​in each iteraction, apparently I can't access them. Also, I created a loop to display each element of the vector on the screen but it doesn't. Can someone help me?

section .data
    global vec
    vec db 53, 
        db 51,
        db 57
    cont equ $-vec
    var1 db 0
section .text
    global _start
_start:
    
    mov r8d, cont
    dec r8d
    
    laco:
        mov ebx, r8d
        mov ecx, vec

        comp_comutar:
            mov eax, [ecx]
            mov edx, [ecx+1]
            cmp eax, edx
            jl n_comutar
            mov [ecx], edx
            mov [ecx+1], eax

        n_comutar:
            inc ecx
            dec ebx
            jnz comp_comutar
    dec r8d
    jnz laco
    
    mov ebx, cont
    mov ecx, vec
    
    loop_print:
        mov [var1], ecx
        inc ecx
        mov eax, 1
        mov edi, 1
        mov esi, var1
        mov edx, 1
        dec ebx
        jnz loop_print

    mov eax, 60
    xor edi, edi
    syscall
1 Answers

Sizes matter

vec db 53, 
    db 51,
    db 57

You have defined the vec array containing bytes, but your code is processing dwords. What happens with these trailing commas? Are you getting an array with 5 elements (53,0,51,0,57) ?

Change

mov eax, [ecx]
mov edx, [ecx+1]
cmp eax, edx
jl n_comutar
mov [ecx], edx
mov [ecx+1], eax

into

movzx eax, byte [rcx]         ;;; mov al, [rcx]
movzx edx, byte [rcx+1]       ;;; mov dl, [rcx+1]
cmp eax, edx                  ;;; cmp al, dl
jl n_comutar
mov [rcx], dl
mov [rcx+1], al
mov [var1], ecx

The ecx dword register holds an address that you store in a byte-sized variable!


Also, I created a loop to display each element of the vector on the screen but it doesn't

The display loop sets up for an API call, but you didn't actually include a syscall instruction. Also, RCX is not call preserved! You can't use it to control your loop.

    mov ebx, vec
loop_print:
    mov eax, 1
    mov edi, 1
    mov esi, ebx
    mov edx, 1
    syscall
    inc ebx
    cmp ebx, vec + cont
    jb  loop_print
Related