I trying to learn assembly language, so I tried to write a program for sorting a number of integers using bubble-sort.
# Sort an array using bubble-sort algorithm
.text
.file "main.s"
.globl _start
_start:
pushq %rbp
movq %rsp, %rbp
subq $28, %rsp
movl $0, -4(%rbp)
movl $23, -8(%rbp)
movl $31, -12(%rbp)
movl $12, -16(%rbp)
movl $43, -20(%rbp)
movl $10, -24(%rbp)
movl $18, -28(%rbp)
leaq -28(%rbp), %rdi
callq bubble_sort
movl -28(%rbp), %eax
callq to_string
movq %rcx, %rdx
callq print_message
addq $28, %rsp
popq %rbp
# terminate program
movq $1, %rax
xorq %rdi, %rdi
syscall
ret
#------------------------------------------
.LBL0:
.ascii "Array before sorting:n"
.LBL1:
.ascii "After sorting array:n"
#------------------------------------------
.globl print_message
print_message:
pushq %rdi
movq $4, %rax
movq $1, %rdi
syscall
popq %rdi
retq
#------------------------------------------
.globl bubble_sort
bubble_sort:
pushq %rbp
movq %rsp, %rbp
movl $0, -4(%rbp)
movq %rdi, -8(%rbp) # Save first element addr
movl $0, -16(%rbp)
loop_0: cmpl $6, -16(%rbp)
jge out_0
movl $0, -24(%rbp) # Not swapped yet...
movl $0, %ecx
movq -8(%rbp), %rax # Restore first element addr
loop_1: cmpl $5, %ecx
jge out1_1
movl (%rax), %r8d
movl 4(%rax), %ebx
cmpl (%rax), %ebx # Compare for swapping
jle out1_0
swap: movl (%rax), %ebx
movl %ebx, -28(%rbp)
movl 4(%rax), %ebx
movl %ebx, (%rax)
movl -28(%rbp), %ebx
movl %ebx, 4(%rax)
movl $1, -24(%rbp) # Swapped!
out1_0: addq $4, %rax
incl %ecx
jmp loop_1
out1_1:
movl -24(%rbp), %ebx
cmpl $0, %ebx # check swap flag
jne out_0
movl -16(%rbp), %ebx
incl %ebx
movl %ebx, -16(%rbp)
jmp loop_0
out_0:
popq %rbp
retq
#------------------------------------------
.globl to_string
to_string:
pushq %rbp
movq %rsp, %rbp
subq $16, %rsp
movl $10, -12(%rbp)
leaq -5(%rbp), %rsi
xorl %ecx, %ecx
loop1: xorl %edx, %edx
divl -12(%rbp)
orl $48, %edx // Convert to ASCII value
movb %dl, (%rsi)
cmpl $0, %eax
je out1
leaq -1(%rsi), %rsi
incl %ecx
jne loop1
out1:
movb $0, -4(%rbp)
addq $16, %rsp
popq %rbp
addl $3, %ecx
movl %ecx, %edx
retq
I think problem comes from the I access the array elements. but I don’t know any way to solve this.
Note: the print_message routine use syscall to write an string to stdout.
syscall 4 in freebsd similar to syscall 1 in linux.
New contributor
Aminavy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.