开发者

Recursion in Mips

开发者 https://www.devze.com 2023-01-29 11:30 出处:网络
I\'m currently trying to figure out how to code a function of finding the lowest integer in MIPS following this algorithm...

I'm currently trying to figure out how to code a function of finding the lowest integer in MIPS following this algorithm...

int Min( int[] A, int low, int high)
{   if (low== high) return A[low];
     int mid = (low+high)/2;
     int  min1 = Min( int[] A, low, mid);
     int   min2 =Min( int[] A, mid +1, high);
     if(min1>min2) return min2;
     return min1;
}

I'm receiving problems as I attempt to code this in MIPS. Here is my current MIPS code. The user inputs up to 6 integers which are stored in an array. The registers $a0, $a1, and $a2 are used as arguments for the function.

  • $a0 = int[]A
  • $a1 = int low //index
  • $a2 = int high //index

Here is the recursion function...

min:
bne $a1, $a2, recur
mul $t4, $a1, 4
add $a0, $a0, $t4
lw $v1, 0($a0) 
jr $ra
# recursion start
recur:
addiu $sp, $sp, -12 #reserve 12 bytes on stack
sw $ra, 0($sp) #push return address
# mid = (low+high)/2 t0 = mid t1= min1 t2=min2 t3 = mid+1
add $t0, $a1, $a2 # t0 = low + high
div $t0, $t0, 2 # t0 = (low+high)/2


# mid1 = min(int[]A,low,mid)
min1:
sw $a2, 4($sp) #push high
addi $t3, $t0, 1 # mid+1
sw $t3, 8($sp) #store mid+1
move $a2, $t0 #change high to mid
jal min #compute
# check
move $t1, $v1 #set up the min1 = return value

# mid2 = min(int[]A,mid+1,high)
min2:
lw $a2, 4($sp) #reload high prior call
lw $a1, 8($sp) #change low to mid+1
jal min #compute
move $t2, $v1 #set as the min2 = return value

confirm:
# return mid2 if mid1 > mid2
bgt $t1, $t2, returnMid2
# else return mid1
move $v1, $t1
j minFinal
returnMid2:
move $v1, $t2
minFinal:
lw $ra, 0($sp)
addiu $sp, $sp, 12 #release stack
jr $ra

The problem is whatever combination of integers I input during the program, I never get the minimum value but rather the number "543976553". I've been looking over my code and notes and开发者_JS百科 I still don't have a clue.


For mid1, try putting the return value on the stack and then moving it to $t1 AFTER mid2 is called. Then compare $v0 with $t1 instead of comparing $t1 with $t2


When using the div command in MIPS, doesn't one need to acquire the quotient from $LO ?

thus your logic for (high+low)/2 might look something like

add $t0, $a1, $a2 # t0 = low + high
addi $t5, $zero, 2 # t5=2
div $t0, $t5 # LO = t0/t5, HI = t0%t5
addi $t0, $LO, 0 # t0 = LO (t0/t5)

some of those lines are written just how I learned to do MIPS but you may have a different style for loading immediate values into a register.

I also can't promise this will fix everything, but at first glance, that is something I noticed.

0

精彩评论

暂无评论...
验证码 换一张
取 消