这是我的代码:
.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
它输出以下内容: 6574839 它应该输出3456789,我相信它在这里无法正常工作
sw $t5, 0($t2) #arr[j] = arr[j + 1]
sw $t4, 0($t3) #arr[j + 1] = arr[j]
但是我不确定为什么它不能正确存储值。 仅应使用指令add,addi,addiu,addu和andi,la,lui,lw,nor,xor,xori或ori,slt,slti,sltiu,sltu,sll,srl,sra, sllv,srlv,srav,sw, sub,subu,beq,bne,j,jal,jr。
答案 0 :(得分:0)
请记住,一个整数需要4个字节,而不仅仅是一个字节。数组的大小是7 * 4个字节。
.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 $t0,$t0,-4 # int takes 4 bytes (no 1 byte)
#addi $t9, $zero, 7
li $t9,28 # size of array = 7*4 bytes
la $a0, test1 #$a0 = base address of array
Loop1:
#addi $t9, $t9, -1 #$t9 = n - 1
addi $t9,$t9,-4 # $t9=n-1
addi $t0, $t0, 4 #i=0
blt $t0, $t9, print #i < n - 1
addi $t1, $zero, 0 #int j = 0;
j Loop2
Loop2:
sub $t8, $t9, $t0 #$t8 = n - i
blt $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, 4 #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