Reputation: 3
I did this MIPS problem that prompts the user to enter at least 4 numbers and print them in ascending order. I was wondering if someone can take a look at it and tell me what you think about it? If I wanted to get it to print in descending order too, how would I get that started? This program is just for fun before I have a real program to do!!!!
.data
array: .space 100
input: .asciiz "Enter at least 4 integers: Enter the number 1000 to exit \n"
output: .asciiz "The array in ascending order: \n"
commas: .asciiz ","
.text
.globl main
main:
la $a1, array #loads a pointer to array into $a1
li $a2,9 #loads 9 into $a2
li $t0,0
li $t1,1000
loops:
la $a0, input #loads input text into $a
li $v0, 4 #loads 4 into $v0 (prints string)
syscall
li $v0, 5 #loads 5 into $v0 (read interger)
syscall
beq $v0,$t1,swap
addi $t0,$t0,4 #add 4 to $t0, save to $t0
sw $v0, ($a1) #stores input into array
addi $a1, $a1,4 #add 4 to $a1, save to $a1
j loops
swap:
la $t4, array #loads array to $t4
la $t1, array #loads array to $t1
addi $t1,$t1,4 #add 4 to $t1, save to $t1
la $t8,array #loads array to $t8
add $t8,$t0,$t8 #add $t8 to $t0, save to $t8
la $t9,array
add $t9,$t0,$t9 #add $t9 to $t0, save to $t9
addi $t9,$t9,-4 #subtracts 4 from $t9, save to $t9
loop:
lw $t2,($t4) #load input into $t2
lw $t3,($t1) #load input into $t3
blt $t2,$t3,loop1 #if $t2 < $t3, go to loops
sw $t3,($t4) #store $t3 in $t4
sw $t2,($t1) #store $t2 in $t1
loop1:
addi $t1,$t1,4 #add 4 to $t1, save to $t1
blt $t1,$t8,loop #if $t1<$t8, go to loop
addi $t4,$t4,4 #add 4 to $t4, save to $t4
move $t1,$t4
addi $t1,$t1,4 #add 4 to $t1, save to $t1
blt $t4,$t9,loop #if $t4<$t9, to go loop
print:
la $a1,array #loads array to $a1
la $a0, output #loads output to $a0
li $v0, 4 #loads 4 into #v0
syscall
loop2:
blez $t0, done #if $t0<=0, go to done
li $v0, 1 #loads 1 into $v0
lw $a0, 0($a1) #load an inout into $a0
syscall
la $a0, commas #loads commas into $a0
li $v0, 4 #loads 4 into $v0
syscall
addi $a1, $a1, 4 #add 4 to $a1, save to $a1
addi $t0, $t0, -4 #subtracts 4 from #t0, save to $t0
j loop2
done:
j done
Upvotes: 0
Views: 5981
Reputation: 14751
Just sort the array descendingly. This shall be the recommended one.
The sorting, like most common ones, is based on the compare-and-swap scheme. In the code it happens at label loop
and loop1
. So you could just change the comparision part of line 44:
blt $t2,$t3,loop1 #if $t2 < $t3, go to loops
to:
bgt $t2,$t3,loop1 #if $t2 > $t3, go to loops
And then the result shall look descending.
Still sort the array ascendingly, while printing the array reversely.
The printing part locates at label loop2
, in which you'll need to change it like replacing line 68:
lw $a0, 0($a1) #load an inout into $a0
with:
add $t1, $a1, $t0
addi $t1, $t1, -4
lw $a0, 0($t1) #load an inout into $a0
and also comment line 73:
addi $a1, $a1, 4 #add 4 to $a1, save to $a1
Upvotes: 1