user2880990
user2880990

Reputation: 29

Finding the minimum value in an array with MIPS

I'm trying to find the minimum value and the sum of an array in MIPS. I can't seem to figure out what I'm doing wrong that it gives out the wrong sum and it doesn't even seem to analyse and return the minimum value of the array.

I am only allowed to use two branch instructions, bne and beq but any other instruction is fair game.

# local variable    register
#   int sum     $s0
#   int min     $s1  (To be used when students enhance the program.)
#   int *p      $s2
#   int *past_last  $s3
#   
    .text
    .globl  main
main:
    la  $s2, arr        # p = arr
    addi    $s3, $s2, 24        # past_last = p + 6
    lw  $s0, ($s2)      # sum = *p
while:
    addi    $s2, $s2, 4     # p++
    beq $s2, $s3, endwhile  # if (p == past_last) goto L2
    lw  $t0, ($s2)      # $t0 = *p
    lw  $t1, -4($s2)        # $t1 = *(p--)
    slt $t2, $t1, $t0       # $t2 = 1 if (*p < *(p--)) else $t2 = 0
    bne $t2, $zero, minimum # if ($t2 != 0) goto minimum
    add $s0, $s0, $t0       # sum += $t0
    j   while
minimum:
    lw  $s1, ($t1)      # min = $t1
    j   while
endwhile:       

Upvotes: 2

Views: 3960

Answers (1)

Michael
Michael

Reputation: 58467

This is not how you move one register to another:

lw  $s1, ($t1)      # min = $t1

That instruction would read a word from the address contained in $t1 and put it in $s1. The correct way to move a register to another would be:

move $s1, $t1

Or, if you don't want to use pseudo-instructions:

or $s1, $zero, $t1

Your method of calculating the minimum is flawed, since you only consider whether the element at position N is less than the element at position N-1. What you should do is initialize min ($s1) to the first element in the array before the loop (like you do with the sum), and then compare that against the current element for each iteration of the loop.


The add, $s0, $s0, $t0 instruction should be placed before the bne $t2, $zero, $minimum instruction. Otherwise the current element won't be added to the sum when the branch is taken (unless your simulator/emulator emulates branch delay slots and your assembler doesn't automatically fill the delay slots for you).

Upvotes: 2

Related Questions