【问题标题】:Binary search in MIPS assemblyMIPS 程序集中的二进制搜索
【发布时间】:2016-10-25 05:17:07
【问题描述】:

我正在尝试在 MIPS 中编写二进制搜索算法。问题来了:

编写一个递归过程 binarySearch,给定一个排序数组 A, 整数 x 和左右索引,搜索 x in A[左..右]。如果 x 存在于 A[left..right] 中,则返回 x(x 的索引),否则通过将值放入 $v0 中返回 -1。在 你的主,调用函数并打印出结果。

我的代码出了点问题。下面代码中显示的所有cmets:

# load $s0: base address
# load $s1: array size
# $s2: the search element
# return index at $v0

.data
myArray:   .word 1, 4, 5, 7, 9, 12, 15, 17, 20, 21, 30
arraySize: .word 11

.text

.globl main

main:
    # perform the first test
    addi $a1, $zero, 15
    jal  binarySearch
    add  $s3, $v0, $zero

exit:
    li $v0, 10
    syscall

binarySearch:
    la   $s0, myArray            # load the base address to $s0
    add  $a0, $zero, $zero       # $a0 is now the first index 0
    lw   $s1, arraySize          # load the array size to $s1
    addi $s1, $s1,  -1           # now $s1 is the last index
    add  $s2, $zero, $a1         # now store the search element into $s2

    j loop                       # do the loop

loop:
    add $t0, $s1, $a0          # have a temp reg to calculate the sum of  high and low
    sra $t1, $t0, 1            # store mid index value into $t1
    add $t1, $t1, $s0          # move to the arr[middle]
    beq $t1, $s2, return       # if the arr[mid] is equal to search value, return mid
    slt $t2, $t1, $s2          # if mid < search, $t2 = 1
    beq $t2, $zero, leftHalf   # if mid > search, go left
    j   rightHalf              # if mid < search, go right

leftHalf:
    add $s1, $t1, -1             # modify the max, max=mid-1
    j do_loop                    # back to the loop

rightHalf:
    addi $t1, $t1,   1
    add  $a0, $zero, $t1         # modify the min, min=mid+1
    j    do_loop                 # back to the loop

return:
    add $ra, $zero, $t1
    jr  $ra

【问题讨论】:

    标签: assembly mips


    【解决方案1】:
    beq $t1, $s2, return       # if the arr[mid] is equal to search value, return mid
    

    这不会将arr[mid] 与搜索值进行比较。它将arr[mid] 的地址与搜索值进行比较。如果您想使用位于内存中的值(而不是其地址),您需要使用 lb/lbu/lh/lw/ld 从内存中加载它。

    例如:

    lw $t1,($t1)
    beq $t1, $s2, return       # if the arr[mid] is equal to search value, return mid
    

    此外,您在 leftHalf/rightHalf 所做的操作不正确,因为您将索引与完整地址混合在一起(即 middle&amp;myArray[middle])。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 2016-07-14
      相关资源
      最近更新 更多