ARM ASM Algorithms (Part 1)
This ARM Assembly program demonstrates sorting two arrays with Bubble Sort. In this series of posts, we will focus on implementations of popular algorithms and recursive subroutines in both 6502 Assembly and ARM as well.
The following snippet is where we set the byte alignment and initalize some output strings. We also initialize two arrays, ary and values here. We import printf and scanf for I/O and equate the boolean values to their bitwise equivalents.
.data
.balign 4
format: .asciz "%d\n"
first: .asciz "first array\n"
second: .asciz "second array\n"
ary: .int 5, 2, 13, 45, 7, 6, 28, 9
values: .int 99, 32, 6, 87, 1, 42, 8, 300, 111, 3
.text
.global main
.extern printf
.extern scanf
.equ false, 0
.equ true, 1
The following subroutine actually handles the bubble sorting. We begin by initializing the registers to the necessary starting indices of the array, as well as a boolean we use for comparison when swapping.
sort:
push {ip, lr}
@ Initialize variables
mov r6, #false
mov r7, #0
mov r8, #1
@ Loop through the array
for:
cmp r8, r5
bge endfor
@ Load values from the array
ldr r2, [r4, r7, lsl #2]
ldr r3, [r4, r8, lsl #2]
@ Compare values and swap if needed
cmp r2, r3
ble endif
mov r1, r2
mov r2, r3
mov r3, r1
mov r6, #true
str r2, [r4, r7, lsl #2]
str r3, [r4, r8, lsl #2]
endif:
add r7, #1
add r8, #1
b for
endfor:
cmp r6, #true
beq do
pop {ip, pc}
The following is the main entrypoint of the program. We push the values of IP and LR onto the stack first, then print the first array. Then, we print, sort, and reprint both arrays to demonstrate a successful parameterized subroutine call in ARM Assembly! Before returning, we pop the values of IP and LR back from the stack.
main:
push {ip, lr}
@ Print a message for the first array
ldr r0, =first
bl printf
@ Sort the first array using Bubble Sort
ldr r4, =ary
mov r5, #8
bl sort
@ Print the sorted first array
mov r7, #0
pfor:
ldr r0, =format
ldr r1, [r4, r7, lsl #2]
bl printf
add r7, #1
cmp r7, r5
blt pfor
@ Print a message for the second array
ldr r0, =second
bl printf
@ Sort the second array using Bubble Sort
ldr r4, =values
mov r5, #10
bl sort
@ Print the sorted second array
mov r7, #0
vfor:
ldr r0, =format
ldr r1, [r4, r7, lsl #2]
bl printf
add r7, #1
cmp r7, r5
blt vfor
pop {ip, pc}