【发布时间】:2019-10-18 11:01:23
【问题描述】:
我的计算机体系结构作业是在 MIPS 汇编中编写一个程序,该程序可以按升序对二维数组进行排序。我用 Java 写了一个可以做到这一点的冒泡排序算法;但是,我对 MIPS 还是很陌生,不知道如何在 MIPS 语法中使用相同的逻辑。
具体来说,我如何在 MIPS 中构造 while-for 循环?我知道 if 和方法调用如何翻译(jal/j/jr 和 bgt/blt/slt),但我无法理解如何构建我的 for 循环
public class D2ArraySort {
public static int[][] switchValsEnd(int[][] a, int i, int j) {
int temp;
temp = a[i][j];
a[i][j] = a[i + 1][0];
a[i + 1][0] = temp;
return a;
}
public static int[][] switchVals(int[][] a, int i, int j) {
int temp;
temp = a[i][j];
a[i][j] = a[i][j + 1];
a[i][j + 1] = temp;
return a;
}
public static int[][] sort(int[][] a) {
while (true) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (j == a[i].length - 1 && i != a.length - 1) {
if (a[i][j] < a[i + 1][0]) {
a = switchValsEnd(a, i, j);
i = 0;
j = -1;
}
} else {
if (j == a[i].length - 1) {
return a;
}
if (a[i][j] < a[i][j + 1]) {
a = switchVals(a, i, j);
i = 0;
j = -1;
}
}
}
}
}
}
public static void main(String[] args) { // don't need main other than to call j sort
int[][] input_data = { // global input_data
{2, 0, -7, -1, 3, 8, -4, 10},
{-9, -16, 15, 13, 1, 4, -3, 14},
{-8, -10, -15, 6, -13, -5, 9, 12},
{-11, -14, -6, 11, 5, 7, -2, -12},
};
int[][] output_data = sort(input_data); // jal sort
for (int i = 0; i < output_data.length; i++) {
System.out.print("( ");
for (int j = 0; j < output_data[i].length; j++) {
System.out.print(output_data[i][j] + ", ");
}
System.out.println(")");
}
}
}
预期输出:
( 15, 14, 13, 12, 11, 10, 9, 8, )
( 7, 6, 5, 4, 3, 2, 1, 0, )enter code here
(-1、-2、-3、-4、-5、-6、-7、-8、)
(-9, -10, -11, -12, -13, -14, -15, -16, )
到目前为止的 MIPS 程序集(我不知道从哪里开始使用 while-for 循环): 也忽略我不完整的主要方法lol
#
# Author: Joshua Baroni
# Date: October 16, 2019
# Description: Sorting 2D array in descending order
#
.text
.align 4
main:
sort:
la $t4, vals #t0 is number up to outer loop
la $t1, vals #t1 is number comparing to inner loop
addi $t1,$t1,4
la $t8,vals
add $t8,$t0,$t8
la $t9,vals
add $t9,$t0,$t9
addi $t9,$t9,-4
loops: lw $t2,($t4) #get number 1 outer loop
lw $t3,($t1) #get number 2 inner loop
bgt $t2,$t3, next #don't need to swap
sw $t3,($t4) #swap
sw $t2,($t1)
next: addi $t1,$t1,4
bgt $t1,$t8,loops #inner loop done?
addi $t4,$t4,4 #yes-increment outer loop
move $t1,$t4
addi $t1,$t1,4
bgt $t4,$t9,loops #outer loop done?
.data
.align 4
Input_data:
.word 2, 0, -7, -1, 3, 8, -4, 10
.word -9, -16, 15, 13, 1, 4, -3, 14
.word -8, -10, -15, 6, -13, -5, 9, 12
.word -11, -14, -6, 11, 5, 7, -2, -12
Output_data:
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
【问题讨论】:
-
二维数组看起来像是在内存中按顺序排列的。所以你可以把它当作一维数组。
标签: algorithm assembly mips mips32