【问题标题】:infinite nested for loop in MIPSMIPS中的无限嵌套for循环
【发布时间】: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 循环有问题。

【问题讨论】:

    标签: for-loop mips


    【解决方案1】:

    在跳转和分支指令之后,您似乎没有为延迟槽留出空间。

    【讨论】:

    • 抱歉,在 MIPS 方面我还是个初学者。延迟槽是什么意思?
    • MIPS 使用管道。在执行一个命令时,会读取下一个命令。为避免浪费阅读下一条命令所花费的精力,即使您进行分支,也会执行下一条命令。包含此类命令的槽(紧邻跳转/分支指令)称为“延迟槽”。无论您是否分支,延迟槽中的命令都会执行。您可以在延迟槽中放入的内容也有一些限制 - 例如,您不能将另一个分支命令放入其中。
    • 好吧,我想弄清楚是什么导致了无限循环,并且能够打印出数组,但它没有排序,所以我想我需要进一步挖掘。我已经更新了我的 MIPS 代码。除了导致无限循环的原因之外,几乎没有任何变化。
    • @PineForestRanch:MARS 默认不模拟延迟槽。它们可以在设置菜单中启用,但默认设置为关闭。
    • @Michael:非常有趣。我从来没有听说过火星。这个 MARS 的目的是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 2021-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多