MIPS汇编:冒泡排序14条指令

MIPS汇编:冒泡排序14条指令

单纯地为了减少汇编指令数,所以就别指望效率了~

在下面也写了C语言对应的代码,希望有助于理解~


MIPS汇编代码:

#$t0:the base address of the array
#$t1:the size of the array(size>=2)
sll $t1,$t1,2
add $t1,$t0,$t1
loop1:
addi $t1,$t1,-4
add $t3,$t0,$zero
loop2:
addi $t3,$t3,4
addi $t2,$t3,-4
lw $t4,0($t2)
lw $t5,0($t3)
slt $t6,$t4,$t5
bne $t6,$zero,unchange
sw $t4,0($t3)
sw $t5,0($t2)
unchange:
bne $t3,$t1,loop2
bne $t2,$t0,loop1

C语言代码:

#include

#define SIZE 8	//SIZE >= 2

int main() {
	int arr[SIZE] = { 7,8,6,5,4,3,1,2 };
	int size = SIZE;
	
	int *base = arr;	//$t0
	int *last;			//$t1
	int *fore;			//$t2
	int *next;			//$t3
	int temp1;			//$t4
	int temp2;			//$t5
	int flag;			//$t6
											//sll $t1,$t1,2
	last = base + size;						//add $t1,$t1,$t0
	do {									//loop1:
		last = last - 1;					//addi $t1,$t1,-4
		next = base;						//add $t3,$t0,$zero
		do {								//loop2:
			next = next + 1;				//addi $t3,$t3,4
			fore = next - 1;				//addi $t2,$t3,-4
			temp1 = *fore;					//lw $t4,0($t2)
			temp2 = *next;					//lw $t5,0($t3)
			flag = temp1 < temp2 ? 1 : 0;	//slt $t6,$t4,$t5
			if (flag == 0) {				//bne $t6,$zero,unchange
				*next = temp1;				//sw $t4,0($t3)
				*fore = temp2;				//sw $t5,0($t2)
			}								//unchange:
		} while (next != last);				//bne $t3,$t1,loop2
	} while (fore != base);					//bne $t2,$t0,loop1

	for (int i = 0; i < size; i++)
		printf("%d ", arr[i]);

	return 0;
}

你可能感兴趣的:(汇编,MIPS,汇编,冒泡排序)