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代碼。幾乎沒有什麼變化,除了造成無限循環的原因之外。 –