This is my code:
.data
test1:
.word 9
.word 8
.word 7
.word 6
.word 5
.word 4
.word 3
size: .word 7
#$t0 stores i
#$t1 stores j
#$t2 stores address of array[j]
#$t3 stores address of array[j + 1]
#$t4 stores value of array[j]
#$t5 stores value of array[j + 1]
#$t6 stores 0 if array[j] >= array[j + 1], 1 otherwise
.text
bubblesort:
addi $t0, $zero, -1 #int i = -1;
addi $t9, $zero, 7
la $a0, test1 #$a0 = base address of array
Loop1:
addi $t9, $t9, -1 #$t9 = n - 1
addi $t0, $t0, 1 #i=0
beq $t0, $t9, print #i < n - 1
addi $t1, $zero, 0 #int j = 0;
j Loop2
Loop2:
sub $t8, $t9, $t0 #$t8 = n - i
beq $t1, $t8, Loop1 #j < n - i - 1
sll $t2, $t1, 2 #$t2 = j * 4
add $t2, $t2, $a0 #t2 = $t2 + baseAddress
lw $t4, 0($t2) #$t4 = arr[j]
addi $t3, $t2, 4 #$t3 = $t2 + 4
lw $t5, 0($t3) #$t5 = arr[j + 1]
slt $t6, $t4, $t5 #$t6 = arr[j] < arr[j + 1]
bne $t6, $zero, Back2 #if($t6 == 1) jump to Back2
sw $t5, 0($t2) #arr[j] = arr[j + 1]
sw $t4, 0($t3) #arr[j + 1] = arr[j]
j Back2 #Jump to Back2
Back2:
addi $t1, $t1, 1 #j++
j Loop2 #Jump to top of Loop2
exit:
addi $v0, $zero, 10
syscall
print:
lw $t3, size
la $t1, test1
li $t2, 0
jal print_loop
print_loop:
beq $t2, $t3, exit
lw $a0, 0($t1)
li $v0, 1
syscall
addi $t2, $t2, 1
addi $t1, $t1, 4
j print_loop
And it outputs this: 6574839 It should output 3456789, I believe it is not working here
sw $t5, 0($t2) #arr[j] = arr[j + 1]
sw $t4, 0($t3) #arr[j + 1] = arr[j]
but I am not sure why it isn't storing the values correctly. This is only supposed to use the instructions add, addi, addiu, addu, and, andi, la, lui, lw, nor, xor, xori, or, ori, slt, slti, sltiu, sltu, sll, srl, sra, sllv, srlv, srav, sw, sub, subu, beq, bne, j, jal, jr.