Reputation: 111
I have been trying to resolve this issue for the last five hours. I have to compare the first index with the last index. If the first < last, they are to be swapped. This works fine if my array has five elements or less. Anything larger and the swapping stops after two iterations. What am I doing wrong?
My subroutine that reverses the array:
ReverseArray:
add $s0, $a0, $0
li $t2, 1
la $s0, array
li $s1, 4
sub $s2, $t0, 1 #lines 177 - 180 finds the last index of the array
mult $s2, $s1
mflo $s2
add $t3, $s2, $s0
swap:
lw $t5, 0($s0)
lw $t4, 0($t3) #stores the element of last index into $t4
sle $t1, $t5, $t4
beq $t1, $0, finish
li $v0, 1 #only in the loop for debug purposes
add $a0, $t1, $0
syscall
add $t6, $t5, $0
sw $t4, 0($s0)
sw $t6, 0($t3)
sub $s2, $s2, 4
add $t3, $s2, $s0
add $s0, $s0, 4
j swap
finish:
add $v1, $s0, $0
jr $ra
Let's say I enter these numbers into my array:
3 6 9 12 15 18
What I get is:
18 15 9 12 6 3
Upvotes: 0
Views: 233
Reputation: 58497
The exit condition for your loop seems to be that the first element is greater than the second, which isn't right if you're trying to reverse the array (you should be comparing addresses or inidices). Your way of updating $t3
also looks odd.
Here's a working loop:
swap:
lw $t5, 0($s0)
lw $t4, 0($t3) #stores the element of last index into $t4
sw $t4, 0($s0)
sw $t5, 0($t3)
sub $t3, $t3, 4
add $s0, $s0, 4
sle $t1,$t3,$s0
beq $t1,$0,swap # repeat until $t3 <= $s0
Upvotes: 1