【发布时间】:2015-10-18 17:18:43
【问题描述】:
因此,在我完成将此冒泡排序代码编码为 MIPS 之后,我尝试了很长一段时间来调试它,但我似乎无法确定我的逻辑可能存在什么问题。请注意,这只是一个 sn-p。如果您觉得缺少某些部分,那是因为我正在单独处理程序的每个部分。假设我已经有一个未排序的数组,其中包含我必须排序的 12 个数字。
我正在使用 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:
每次在mars中运行汇编,很长一段时间都没有输出。现在我知道冒泡排序在处理大型数组时效率很低,但这只有 12 个元素。所以我的猜测是嵌套的 for 循环有问题。
【问题讨论】: