我已被指派实现一个排序数组函数,该函数按照从最小到最大的数字顺序对数组的内容进行排序。数组如下:
testArray:
.word 9
.word 8
.word 7
.word 4
.word 5
.word 6
.word 3
.word 2
.word 1
.word 0
当我发送这个数组进行排序时,我的输出如下:
A[0] = 9
A[1] = 8
A[2] = 7
A[3] = 4
A[4] = 5
A[5] = 6
A[6] = 3
A[7] = 2
A[8] = 1
A[9] = 0
Sorting Array Contents.
A[0] = 8
A[1] = 7
A[2] = 4
A[3] = 5
A[4] = 6
A[5] = 3
A[6] = 2
A[7] = 1
A[8] = 0
A[9] = 9
Program terminated.
这是我用来对数组内容进行排序的算法
void sortArray(int A[], int entryCount) {
int i;
int j;
int temp;
for (i = entryCount - 1; i > 0; i--) {
for (j = 0; j < i; j++) {
if (A[j + 1] < A[j]) {
temp = A[j];
A[j] = A[j + 1];
A[j + 1] = temp;
}
}
}
}
我转换为mips如下:
# Temporary registers
#
# $t0 = address of teststring
# $t1 = n
# $t2 = i
# $t3 = j
# $t4 = temp
# $t5 = A[j]
sortArray:
move $t0, $a0 # Load array address into $t0
move $t1, $a1 # $t1 = n
move $t2, $zero # set i = 0
move $t3, $zero # set j = 0
move $t4, $zero # set temp = 0
move $t2, $t1 # set i = entrycount
b condition_test
condition_test:
subi $t2, $t2, 1 # i--
bgtz $t2, condition_test2
b end
condition_test2:
blt $t3, $t2, condition_test3 # j < i
b condition_test
condition_test3:
lw $t5, 0($t0) # A[j]
addi $t0, $t0, 4
lw $t6, 0($t0) # A[j+1]
sub $t0, $t0, 4
blt $t6, $t5, loop_top # (A[j+1] < A[j])
b condition_test2
loop_top:
move $t4, $t5 # temp = A[j]
sw $t6, 0($t0) # A[j] = A[j+1]
add $t0, $t0, 4
sw $t4, 0($t0) # A[j+1] = temp
addi $t3, $t3, 1 # j++
b condition_test2
end:
jr $ra
希望有人可以了解我的转换错误。感谢。