I am very new to MIPS and this is a homework assignment, so I'm really just looking for a clue to get me going. :) I have looked around for similar questions but didn't find anything that was what I needed, so I'm sorry that this has been asked before. I am writing a bubble sort in PCSpim, and I think I am pretty good with the code, except for swapping.
Here is the pseudocode:
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
I think it involves getting the addresses of each element, checking to see if the first is greater than the second, and completing a swap via a swap function. Here is what I have:
.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
As you can see, I've left a piece of the middle blank, because I am not sure what to do to get the two elements and compare them. I found something online that said I could swap elements via move and temporary registers, but I don't see the connection between getting these elements and then swapping them. I realize the code is likely not optimal and there may be shortcuts, but I am very much a beginner on this.
Any advice would be appreciated! Thank you in advance.