0
所以我试了很长时间来调试这个后,我完成编码这个气泡排序代码MIPS,我似乎无法指出什么问题可能与我的逻辑。请注意,这只是一个片段。如果你觉得缺少某些部分,那是因为我正在单独处理程序的每个部分。假设我已经有了一个未排序的数组,里面充满了我必须排序的12个数字。无限嵌套for循环在MIPS
我正在使用mars_4.5来检查我的输出。
高级代码:
// arr[i] will be in the correct spot after every iteration
for (int i = n-1; i > 0; i--)
for (int j = 0; j < i; j++) // Put arr[j] and arr[j+1] in order
if (arr[j] > arr[j+1]) // If they are out of order, swap them
{
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
重要信息:
# $s1 = n size of the array
# $s2 = i outer loop counter
# $s3 = j inner loop counter.
# $s5 is the address of the size (= 12)
# $s0 is the starting address of the array
编辑:现在的MIPS代码工作。
MIPS代码:
lw $s1, 0($s5) # Load the size of the array into $s1.
addi $s2, $s1, -1 # Perform the initialization i = n - 1
For1: # outer for loop
bltz $s2, Exit # Checks if i < 0. If true, exit out of the outer for loop.
add $s3, $zero, $zero # sets j to zero after each iteration of the inner loop.
j For2 # executes the nested for loop.
Update1:
addi $s2, $s2, -1 #i--
j For1 # exceute back to the outer for loop.
For2: # inner for loop
slt $t0, $s3, $s2
bne $t0, 1, Update1 # If the inner loop fails, go back to outer loop
sll $t3, $s3, 2
add $t3, $s0, $t3
lw $t1, 0($t3) # $t1 = arr[j]
lw $t2, 4($t3) # $t2 = arr[j + 1]
slt $t0, $t2, $t1
bne $t0, 1, Update2 # if the conditional fails
sw $t2, 0($t3) # store contents of $arr[j + 1] into arr[j]
sw $t1, 4($t3) # store contents of $arr[j] into arr[j + 1]
Update2:
addi $s3, $s3, 1 # j++
j For2
Exit:
我每次运行在火星汇编,就没有输出很长一段时间。现在我知道冒泡排序对于大数组非常低效,但这只是12个元素。所以我的猜测是嵌套的for循环是错误的。
对不起,我还是MIPS的初学者。延迟插槽是什么意思? –
MIPS使用管道。当执行一个命令时,读取下一个命令。为了避免花费在阅读下一个命令上的努力,即使你分支,下一个命令也会被执行。包含这样的命令的插槽(紧接着跳转/分支指令)被称为“延迟时隙”。无论您是否分支,延迟插槽中的命令都会执行。您可以将什么放入延迟插槽也有一些限制 - 例如,您不能将另一个分支命令放到那里。 – PineForestRanch
好吧,我想确定是什么导致无限循环,并能够打印出数组,但它没有排序,所以我想我需要进一步挖掘。我已经更新了我的MIPS代码。几乎没有什么变化,除了造成无限循环的原因之外。 –