使用Mips程序集

时间:2017-01-02 07:17:43

标签: mips

我遇到了麻烦。我尝试使用mips程序集中的递归来制作二进制搜索算法,但是我有一些错误,我不明白如何解决它们。

我有一个包含10个整数的数组,我假设数组已经排序。 这是我的代码,我感谢任何帮助,并提前感谢..

         .data
arr:     .word 40    
arrMsg:  .asciiz "Enter the array : \n"
posMsg:  .asciiz "This value exist in the array and its position is "
pos:     .word 0
newline: .asciiz "\n"
valMsg:  .asciiz "Enter the value you search for : \n"
val:     .word 0
notfound:.asciiz "the value doesn't exist in the array !! \n"
     .text
main:   
     # print the array message
     li $v0, 4
     la $a0, arrMsg
     syscall

     # read the array from the user
     # put $s0 = i 
     add $s0, $zero, $zero           # i = 0
for:
    beq $s0, 40, end

    li $v0, 5
    syscall

    sw $v0, arr($s0)                 #  input arr[i]
    addi $s0, $s0, 4                 # i = i + 4

    j for
end:      

    # print value message
    li $v0, 4
    la $a0, valMsg
    syscall

    # read the value from the user
    li $v0, 5
    syscall

    # store the value in the val variable
    sw $v0, val

    ################################################
    ## put $s0 = start , $s1 = middle , $s2 = end ##
    ################################################
    li $s0, 0
    li $s2, 9  

    jal BinarySearch

    li $v0, 10
    syscall

    ############################################################################################################

BinarySearch:

    # middle = (start + end ) / 2
    add $t0, $s0, $s2                   # $t0 = start + end
    sra  $s1, $t0, 1                    # $s1 = $t0 / 2

    # save $ra in the stack
    addi $sp, $sp, -4
    sw $ra, 0($sp)

    # base case
    ble $s2, $s0, returnNegative1       # if (end <= start) 

    lw  $t1, arr($s1)                   # $t1 = arr[middle]
    lw  $t2, val                        # $t2 = val
    beq $t1, $t2, returnMiddle          # if (arr[middle] == val)

    blt $t2, $t1, returnFirstPart       # if (val < arr[middle])

    bgt $t2, $t1, returnLastPart        # if (val > arr[middle])  

    returnNegative1:
       li $v0, -1
       j Exit       
    returnMiddle:
       move $v0, $s1                    # return middle
       j Exit   

    returnFirstPart:
           move $t3, $s1                # temp = middle     
           addi $t3, $t3, -1            # temp --
           move $s2, $t3                # end = temp
           jal BinarySearch
       j Exit

    returnLastPart:                             
       move $t3, $s1                    # temp = middle
       addi $t3, $t3, 1                 # temp++
       move $s0, $t3                    # start = temp
       jal BinarySearch
       j Exit   

Exit:   
    lw $ra, 0($sp)
    addi $sp, $sp, 4`
    jr $ra

1 个答案:

答案 0 :(得分:1)

mul $s4, $s1,4

这是问题,因为它不是真正的正确索引,因为整数需要4个字节 所以你从中间得到

$s4

只是逻辑地址而不是真正的地址,你需要将它乘以4

lw  $t1, arr($s4)                   # $t1 = arr[middle]

然后使用if (end < start)作为地址

ng-bind

也应该是停车条件的错误 {{}}不是(&lt; =)

抱歉我的英文