我不确定我的代码到底发生了什么。当我尝试使用lw
和sw
交换数组中的值时,会出现问题。该程序应该按升序对数组进行排序,然后输出。
.text
.globl __start
__start:
la $t0, array # t0 = address of array
lw $t1, count # t1 = count, exit loop when it goes to 0
loop:
lw $t2, ($t0) # t2 = element in array
lw $t4, count # t4 = count, for innerLoop
add $t3, $t0, 4 # t3 = address of next array element
innerLoop:
lw $t5, ($t3) # t5 = element in array
ble $t2, $t5, greater # if element in t2 is >= element in t5 goto greater
sw $t2, ($t3) # store element in t2 into the t3 array address
sw $t5, ($t0) # store element in t5 into the t0 array address
lw $t2, ($t0) # t2 = new element in t0 array address
greater:
add $t4, $t4, -1 # t1 -- -> counter --
add $t3, $t3, 4 # t3 = address of next array element
bnez $t4, innerLoop # if innerLoop count != 0 go to innerLoop
add $t1, $t1, -1 # t1 -- -> counter --
addi $t0, $t0, 4 # t0 = address of next array element
bnez $t1, loop # if loop count != 0 go to loop
la $t0, array # t0 = address of array
lw $t1, count # t1 = count, exit loop when it goes to 0
lw $t2, ($t0) # lw in address t0 into t2
move $a0, $t2 # Display the first element in array
li $v0, 1
syscall
add $t1, $t1, -1 # t1 -- -> counter --
add $t0, $t0, 4 # increment counter to point to next word
displayLoop:
lw $t2, ($t0) # t2 = next element in array
la $a0, comma # Display ", "
li $v0, 4 # a0 = address of message
syscall # v0 = 4 which indicates display a string
move $a0, $t2 # Display element in array
li $v0, 1
syscall
add $t1, $t1, -1 # t1 -- -> counter --
add $t0, $t0, 4 # increment counter to point to next word
bnez $t1, displayLoop # if count != 0 the go to displayLoop
la $a0, crlf # Display "cr/lf"
li $v0, 4 # a0 = address of message
syscall # v0 = 4 which indicates display a string
li $v0, 10 # End Of Program
syscall
.data
array: .word 3, 4, 2, 6, 12, 7, 18, 26, 2, 14, 19, 7, 8, 12, 13
count: .word 15
comma: .asciiz ", "
crlf: .asciiz "\n"
这是我得到的输出:
2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 26, 167780396, 19, 18, 15, 14, 13, 12, 12, 8, 7
答案 0 :(得分:0)
我设置外部循环if语句来检查t1是否大于1,因为当它变为1时t0是数组中的最后一个元素而没有其他任何东西需要检查