在MIPS程序集中进行二进制搜索

时间:2016-10-25 05:17:07

标签: assembly mips

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

  

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

我的代码出了问题。以下代码中显示的所有注释:

# 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

1 个答案:

答案 0 :(得分: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与{{1} })。