给定已经排序数组{1,2,3,4,5,6,7,8,9,20,25,30}并且数组中的元素大小定义为word,使用Binary Search找到x=7并将其存到地址为0x0000000c的位置
本来以为需要再定义一个空的数组进行二向分后的存储,后来发现当所需要的数字大于中位数时只需要将指向数组的指针移动到每个中位数所在的位置即可,小于中位数时不需要移动
废话不多说直接上代码
.global _start
_start:
ldr r6, =0x0000000c // Load the specific address into r6
ldr r0, =arr // Address of the array
ldr r1, =size // Load size of the array
mov r3, #7 // Number we are searching for in the array
binary_search:
mov r2, r1, lsr #1 // Divide size by 2 to find the middle
mov r1, r2 // Update size to the new size
push {r2} // Save the current middle index on the stack
sub r2, r2, #1 // r2 = r2 - 1
lsl r2, r2, #2 // r2 = r2 * 4 (assuming 32-bit integers)
add r0, r0, r2 // Update base address of the array
ldr r2, [r0] // Load the element at the new array base address
cmp r3, r2 // Compare the element with the target number
beq found // If equal, go to found
blt less_than_middle // If the element is less, go to less_than_middle
bgt greater_than_middle // If the element is greater, go to greater_than_middle
less_than_middle:
pop {r2} // Restore previous middle index
b binary_search // Continue the binary search
greater_than_middle:
pop {r2}
add r0, r0, r2, lsl #2 // Adjust the address for the upper half of the array
b binary_search
found:
str r2, [r6] // Store the found index at address 0x0000000c
exit:
mov r7, #1 // Exit syscall
swi 0 // Software interrupt to trigger the syscall
.data
arr: .word 1,2,3,4,5,6,7,8,9,20,25,30
size: .word 12
下面附上运行结果
可以看到0x0000000c的位置已经变为7
最后附上老师给的比较好用的arm在线编辑平台链接