这里是我对cmets问题的解决方法来解释一下。
我没有实现所有值都相同的特殊情况,但这不是一个非常困难的添加。只是最后一个beq $a1, $a2, end
这里还有很多特殊情况,比如检查最小和次小的保留空间中是否存在值。
也没有用户输入,因为不清楚这是否是最终意图。
.data
values: .word 13 , 16 , 16, 7, 7 # Array contents
.text
main:
li $a0, 5 # Loading array size
la $a3, values
move $a2, $zero # Second Smallest
move $a1, $zero # Smallest
loop:
beq $t1, $a0, fin # If iterator is equal to the high value entered break
lw $t5, 0($a3) # Loading the element at the given array address
bnez $a2, sSmallestExists # Branch if $a2 has a value -- there is a second smallest value
bnez $a1, smallestExists # Branch if $a1 has a valuel -- there is a smallest value
move $a1, $t5 # Set $a1 to the value stored at $t5 -- set the smallest value
j reloop # jump to reloop
smallestExists:
blt $t5, $a1, setSmallest # Branch if the current value is less than the smallest value
move $a2, $t5 # Set the second smallest to the current value
j reloop # jump to reloop
sSmallestExists:
bge $t5, $a2, reloop # If the current value in $t5 is greater than the second smallest reloop
blt $t5, $a1, setSmallest # Branch if the current value in $t5 is less than the smallest
beq $t5, $a1, reloop # If the current value in $t5 is equal to the smallest reloop
move $a2, $t5 # Set the second smallest to the current value
j reloop
setSmallest:
move $a2, $a1 # Set the current smallest value ($a1) to be the second smallest ($a2)
move $a1, $t5 # Set the current value ($t5) to be the smallest ($a2)
reloop:
addi $t1, $t1, 1 # Add one to the iterator
add $a3, $a3, 4 # Add 4 to progress the array
j loop # Go back to the top of the loop
fin:
li $v0, 1 # Output second smallest value
la $a0, ($a2)
syscall
li $v0, 10 # Syscall 10 to indicate end of program
syscall