Arrays 如何在MIPS中找到第二个最小值?

Arrays 如何在MIPS中找到第二个最小值?,arrays,mips,minimum,Arrays,Mips,Minimum,在本项目中,您将实现一个MIPS应用程序 找到第二个最小值 在声明的数组中。下面给出了如何定义整数数组 价值观 包含数组元素,大小描述数组长度 给出了一些示例数组和预期输出 n在下面 数组:[13,16,16,7,7] 你的输出:13 数组:[8,8,8] 你的输出:没有第二个最小的 数组:[7,7,6] 你的输出:7 数组:[8,7] 你的输出:8 数组:[3,3,5,3,3,5] 您的输出:5以下是我对该问题的解决方案,并附有注释进行解释 我没有实现所有值都相同的特殊情况,但这不是一个非常

在本项目中,您将实现一个MIPS应用程序 找到第二个最小值 在声明的数组中。下面给出了如何定义整数数组

价值观 包含数组元素,大小描述数组长度

给出了一些示例数组和预期输出 n在下面

数组:[13,16,16,7,7] 你的输出:13

数组:[8,8,8] 你的输出:没有第二个最小的

数组:[7,7,6] 你的输出:7

数组:[8,7] 你的输出:8

数组:[3,3,5,3,3,5]
您的输出:5

以下是我对该问题的解决方案,并附有注释进行解释

我没有实现所有值都相同的特殊情况,但这不是一个非常困难的添加。只是最后一个
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

使用所需的排序算法对数组进行升序排序,然后在排序后的数组上迭代,直到找到与第一个元素不相等的元素,或者到达数组的末尾。