Bubble Sort in MIPS

I am trying to sort a string that is being read in, but it is not doing this correctly. Does anyone see what I am doing wrong?

Thanks,
Kevin

.data
Prompt: .asciiz "Enter a sentence -> "
Prompt2:.asciiz "Number of characters = "
NumChar:.word 0
NewLn: .asciiz "
"

.text
.globl main
main:
la $a0, Prompt #Print Prompt
li $v0, 4
syscall

#-----------------------Read in String----------------------------------#
li $v0, 8 #Read in String
move $s0, $a0 #Copy to $s0
syscall

#-----------------------Get/Print number of chars in the string-------=#
la $a0, Prompt2 #Print Prompt2
li $v0, 4
syscall

move $a0, $s0 #Copy string to $a0 to pass to numch function
jal numch #Get Number of chars

sw $v0, NumChar
move $a0, $v0 #Copy number of chars into $a0, and print
la $v0, 1
syscall

#-----------------------Sort the string------------------------------------#
move $v0, $s0 #Copy string to $v0 to pass to sort function
jal sort #Sort the string

move $s0, $v0 # Save sorted string into $s0


#---------------------Print the sorted string-------------------------------------#

la $a0, NewLn #Print Blank Line
li $v0, 4
syscall

move $a0, $s0
li $v0, 4
syscall

li $v0, 10 # return to kernel from main routine
syscall
.end main

#--------------------------------END MAIN---------------------------------------------------------------------#


#----------------------Number of Chars--------------------------------------#

numch: li $v0, -1 #Set $v0 to -1
numch2: lbu $t0, 0($a0) #Load one char into $t0
addiu $a0, $a0, 1 #Increment to the next character
addi $v0, $v0, 1 #Add one to the character counter
bne $t0, $zero, numch2 #If the character is not zero, go through the loop again
addi $v0, $v0, -1 #Subtract one (to compensate for the return key in the string)
jr $ra #Retrun to the calling function

#----------------------Bubble Sort------------------------------------------------#

sort:
move $t9, $v0 #t9=Address of string
lw $t1, NumChar # $t1 = NumChar
li $t0, 0 # $t0 = 0 (i)

for1:
beq $t1, $t0, exit # if $t0 == numchar, exit
addi $t4, $t0, -1 # $t4(J) = counter-1

for2:
bltz $t4, exit2 # j < 0
mul $t5, $t4, 2 # $t5 = 2 * j

add $t5, $t9, $t5 # $t5 = &a[j]

lb $t2, 0($t5) # $t2 = a[j]
lb $t3, 1($t5) # $t3 = a[j+1]
ble $t3, $t2, else # a[j+1] >= a[j]
j swap

else:
addi $t4, -1 # --j
j for2

exit: move $v0, $t9 #Return $t9 (sorted string)
jr $ra

exit2:
addi $t0, 1 # ++i
j for1

swap: sb $t3, 0($t5)
sb $t2, 2($t5)
j for2

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories