MIPS中的二进制搜索不起作用

时间:2015-11-10 20:04:44

标签: mips binary-search

基本上我有一个实验室,它是关于使用MIPS执行二分查找 我试图存储该值,但似乎答案不正确,并且该值无法存储在我想要的寄存器中 我无法弄清楚问题出在哪里 我试图搜索15的索引并将答案存储到$s3

以下是我的代码:

# load $s0: base address
# load $s1: array size
#      $s2: the search element
# return index at $v0
.text 
.globl main
main:
    # perform the first test
    addi $a1, $zero, 15
    jal  binary_search
    add  $s3, $v0,   $zero

exit:
    li $v0, 10
    syscall

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

    j do_loop                    # do the loop

do_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, front_half   # if mid> search, go left
    j   back_half                # if mid< search, go right 

front_half:
    add $s1, $t1, -1             # modify the max, max=mid-1
    j do_loop                    # back to the loop
back_half:
    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

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

0 个答案:

没有答案