calculate minimum of array

971 Views Asked by At

I need to find the minimum of an array of numbers stored in $a2, but it is only outputting the last number.

For example, if i input 1, 2, 3, it will output the minimum as 3.

Any suggestions? This is the section of code

Minimum:

    beq $t1,$t5,exit
    add $a1,$a1,4       
    add $t1,$t1,1

    lw  $t0,0($a1)

    bge $t0,$t2,loop 
    move    $t2,$t0  
loop:

    j   Minimum
exit:

    li  $v0,4
    la  $a0,min #print "Mininum= "
    syscall

    li  $v0,1
    move    $a0,$t2     
    syscall
1

There are 1 best solutions below

0
On BEST ANSWER

Writing like this:

Minimum:
    beq $t1,$a1,exit
    add $t1,$t1,1
    lw  $t0,0($a2)  #load next array value
    add $a2,$a2,4   #doing this before would skip first element of array
    bge $t0,$t2,loop
    move    $t2,$t0  #if minimum found

Also doing:

lw  $t2,0($a2)  #set minimum to array[0]
move    $a1,$t1     #move count to a1

is wrong since $a2 won't be the start address of array. After minimum, $a2 would be at the address after the last element of array.

Instead write:

la $a2,array
lw  $t2,0($a2)  #set minimum to array[0]
move    $a1,$t1     #move count to a1

Modifying Minimum gives answer for me. If you still have problem, give your complete code. I will read it and tell your mistake.