我是MIPS的新手,这是一项家庭作业,所以我真的只是想找个让我走的路。 :)我一直在寻找类似的问题,但没有找到我需要的东西,所以我很抱歉以前曾经问过这个问题。我正在PCSpim中写一个冒泡排序,我认为除了交换之外,我对代码非常满意。
这是伪代码:
lastUnsorted = length - 1
sortedFlag = 0
while(lastUnsorted >= 1 and sortedFlag == 0) do
sortedFlag = 1
for test = 0 to lastUnsorted-1 do
if(numbers[test] > numbers[test+1] then
temp = numbers[test]
numbers[test] = numbers[test+1]
numbers[test+1] = temp
sortedFlag = 0
end if
end for
lastUnsorted = lastUnsorted -1
end while
我认为它涉及获取每个元素的地址,检查第一个是否大于第二个元素,并通过交换函数完成交换。这就是我所拥有的:
.data
numbers: .word 20, 30, 10, 40, 50, 40, 30, 25, 10, 5
length: .word 10
sortedFlag: .word 0
lastUnsorted: .word 9
test: .word 0
.text
.globlmain
main:
la $11, numbers
lw $12, length
lw $13, sortedFlag
lw $14, lastUnsorted
lw $15, test
j while
end_main:
#####################################################################
while:
li $16, 1
blt $14, $16, end_while #program is completed
li $17, 0
bne $13, $17, end_while #program is completed
addi #13, 1 #make sortedFlag == 1
j bubble_sort #jump to the bubble sort
bubble_sort:
bge $15, $14, go_back #if test is greater than or equal to lastUnsorted, end
####stuff for swap
# find address of first, then second and store each in t0 and t1
# check the value at $t0 is greater than val at $t1; if so, call swap function
addi $15, $15, 1 #add one to test after swap or no swap
j go_back #jump out of sorting loop
go_back:
addi $14, $14, -1 #subtract one from lastUnsorted
j while #jump back to while loop to start again
swap:
move $t2, $t0 #swap with temporary registers??
move $t0, $t1
move $t1, $t2
addi $13, $13, -1 #make sortedFlag == 0 IF a swap is completed
end_while:
li $vo, 10 #prog is done
syscall
正如你所看到的,我留下了一块中间的空白,因为我不知道如何做到这两个元素并进行比较。我在网上找到了一些说我可以通过移动和临时寄存器交换元素的东西,但是我没有看到获取这些元素然后交换它们之间的联系。我意识到代码可能不是最优的,并且可能有快捷方式,但我是一个非常初学者。
任何建议将不胜感激!先感谢您。