SORT
使用冒泡排序对整数数组进行排序,这种排序虽然不是最快的,但却是最简单的。
C语言代码
#include<stdio.h>
#include<iostream>
using namespace std; void swap(int v[], int k)
{
int tmp;
tmp = v[k];
v[k] = v[k + ];
v[k + ] = tmp;
} void sort(int v[], int n)
{
int i, j;
for (i = ; i < n; i += )
for (j = i - ; j >= && v[j] > v[j + ]; j -= )
swap(v, j);
} int arr[] = { ,,,,,, }; int main()
{
sort(arr, );
for (int i = ; i < ; i++)
printf("%d ", arr[i]);
return ;
}
MIPS代码
#sort
.data
array: .word ,,,,,,
str_old: .asciiz "old array:\n"
str_new: .asciiz "new array:\n"
blank: .asciiz " "
enter: .asciiz "\n"
.text
.globl main
main:
la $a0,str_old
li $v0,
syscall #print str_old string
jal print_array #print old arrry la $a0,array #array name
li $a1, #array length
jal sort la $a0,str_new
li $v0,
syscall #print str_new string
jal print_array #print new arrry li $v0,
syscall # exit print_array:
li $a1,
la $a2, array
loop1: blez $a1, over1
lw $a0, ($a2)
li $v0,
syscall la $a0, blank
li $v0,
syscall addi $a2, $a2,
addi $a1, $a1, -
j loop1
over1:
la $a0, enter
li $v0,
syscall
jr $ra #$a0: arrry
#$a1: k
swap:
sll $t1,$a1, #reg $t1 = k *
add $t1,$a0,$t1 #reg $t1 = v + k * lw $t0,($t1) #reg $t0(tmp) = v[k]
lw $t2,($t1) #reg $t2 = v[k + ] sw $t2,($t1) #v[k] = v[k + ]
sw $t0,($t1) #v[k+ ] = tmp(v[k])
jr $ra
#$a0: v
#$a1: n
#$s0: i
#$s1: j
sort:
addi $sp,$sp,- #make room on stack for registers
sw $ra,($sp)
sw $s3,($sp)
sw $s2,($sp)
sw $s1,($sp)
sw $s0,($sp) move $s2,$a0 #save v
move $s3,$a1 #save n move $s0,$zero #i =
for1tst:
slt $t0,$s0,$s3 #if(i < n),reg $t0 = 1
beq $t0,$zero,exit1 addi $s1,$s0,-
for2tst:
slti $t0,$s1, #if(j < 0),reg $t0 = 1
bnez $t0,exit2 #go to exit2 if(j < )
sll $t1,$s1, #$t1 = j *
add $t2,$s2,$t1 #$t2 = v + j *
lw $t3,($t2) #$t3 = v[j]
lw $t4,($t2) #$t4 = v[j + ]
slt $t0,$t4,$t3 #if(v[j + 1] < v[j]),reg $t0 = 1
beq $t0,$zero,exit2 #go to exit2 if(v[j + ] >= v[j]) move $a0,$s2 #first parameter is v
move $a1,$s1 #second parameter is j
jal swap addi $s1,$s1,- #j--
j for2tst #continue inner loop
exit2:
addi $s0,$s0,
j for1tst
exit1:
lw $s0,($sp)
lw $s1,($sp)
lw $s2,($sp)
lw $s3,($sp)
lw $ra,($sp)
addi $sp,$sp,
jr $ra