I was trying to solve the question where I need to write a function that return the minimum and maximum of an integer array of size N in MIPS language I tried but every time it return the minimum and maximum I have put as default and I couldn't figure out why my code is:
.data
en: .asciiz "Enter N"
val: .asciiz "enter the values: "
min: .asciiz "the min is: "
max: .asciiz "the max is: "
.text
li $v0 4
la $a0 en
syscall
li $v0 5
syscall
blez $v0 End
move $t0 $v0 #t0 contain N
li $v0 9
mul $a0 $t0 4
syscall
move $t1 $v0 #s1 contain the array
li $v0 4
la $a0 val
syscall
li $t2 1
#filling the array
Fill:
bgt $t2 $t0 endFill
li $v0 5
syscall
sw $v0 ($t1)
addi $t2 $t2 1
addi $t1 $t1 4
j Fill
endFill:
mul $t3 $t0 4
sub $t1 $t1 $t3
move $a0 $t0
move $a1 $t1
jal minmax
move $t2 $v0 #max
move $t3 $v1 #min
#print the min and max
li $v0 4
la $a0 min
syscall
li $v0 1
move $a0 $t3
syscall
li $v0 4
la $a0 max
syscall
li $v0 1
move $a0 $2
syscall
j End
minmax:
move $s0 $a0 #s0 contain N
move $s1 $a1 #s1 contain the array
li $s2 0 #for the loop
li $s3 0 #for the max
li $s4 23456 #for the min
Loop:
bge $s2 $s0 EndLoop
lw $s5 ($s1) #s5 contain the element of the list
bgt $s5 $s3 tomin
move $s3 $s5
j tomin
tomin:
blt $s5 $s4 goagain
move $s4 $s5
j goagain
goagain:
addi $s2 $s2 1
addi $s1 $s1 4
j Loop
EndLoop:
move $v0 $s3
move $v1 $s4
jr $ra
End:
li $v0 10
syscall
I tried printing the value of the min and max (s4 and s3 in the function minmax in the part EndLoop) and there it also show me the default values I have put so I guess it didn't enter the loop but I can't figure out why I'm still new to this language so I'm struggling a bit thank you in advance
CodePudding user response:
The condition in this part is reversed.
bgt $s5 $s3 tomin
move $s3 $s5
j tomin
tomin:
blt $s5 $s4 goagain
move $s4 $s5
j goagain
goagain:
$s3
is for the maximum value, so you will want to skip updating $s3
if the candidate value is smaller than $s3
.
In the same way, you will want to skip updating the minimum value $s4
if the candidate value is larger than $s4
.
Therefore, bgt
and blt
in this part should be swapped.
(whether to update when the candidate value equals to $s3
or $s4
is not a large issue)