使用ARM汇编完成Binary Search

给定已经排序数组{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在线编辑平台链接

https://cpulator.01xz.net/?sys=arm 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值