我一直在关注这个问题,我无法弄清楚什么是不能正常工作的。基本上我需要做的是获取一个整数数组,并使用选择排序对它们进行排序,我已经完成了这个是java和c,所以我知道它是如何工作的,但是汇编工作正常。
以下是我在汇编中的代码:
li $t0, 0 #$t0 is used as i
addi $t1, $t0, 1
li $t2, 0 #t2 is used as j
sll $t5, $t1, 2
ILoop:
JLoop:
lw $t3, array($t2)
lw $t4, array($t5)
ble $t3, $t4, Jelse
sw $t3, temp
sw $t4, array($t2)
lw $t4, temp
sw $t4, array($t5)
Jelse:
addi $t1, $t1, 1
sll $t5, $t1, 2
blt $t1, 4, JLoop
Ielse:
addi $t0, $t0, 1
sll $t2, $t0, 2
blt $t0, 3, ILoop
输出示例:
排序前的数组:
25 17 31 13 2
排序后的数组:
13 2 0 17 25
我错过了什么?或者我错放了什么,请帮忙!谢谢!
答案 0 :(得分:2)
它可能就像没有足够的循环一样简单(你的内循环在j<len-1
循环,而外循环在i<len-2
)。您可以通过单步执行SPIM中的代码来找到答案
这是一个有效的实施方案供您参考:
# Sorts in ascending order
li $t0, 0 #$t0 is used as i
ILoop:
sll $t2,$t0,2 # pos = i (scaled for word elements)
addiu $t5,$t2,4 # j = i+1 (scaled for word elements)
JLoop:
lw $t3, array($t2) # array[pos]
lw $t4, array($t5) # array[j]
ble $t3, $t4, JElse
move $t2,$t5 # pos = j
JElse:
addiu $t5,$t5,4
blt $t5,20,JLoop # 20 = array_length * sizeof(word)
# if (pos != i) swap(array[pos], array[i])
sll $t1,$t0,2
beq $t2,$t1,SkipSwap # skip if pos==i
lw $t3, array($t2) # $t3 = array[pos]
lw $t4, array($t1) # $t4 = array[i]
sw $t4, array($t2) # array[pos] = array[i]
sw $t3, array($t1) # array[i] = array[pos]
SkipSwap:
addi $t0, $t0, 1
blt $t0, 4, ILoop # run ILoop while i<array_length-1