          .data
 __txt1_: .asciiz "\nThe source data is: "
 __txt2_: .asciiz "\nThe sorted data is: "
 __xxxx_: .asciiz ", "
 __data_: .word 4,3,5,1,2

          .text
          .globl main  
main:	
        li   $v0 4		# 印出__txt1_內的東東
	la   $a0 __txt1_
	syscall
        la   $a0 __data_	# call routine (display)(印出原始data)
        li   $a1 5           
	jal  display

        la   $a0 __data_	# call routine (sort)(排列data)
        li   $a1 5
        jal  sort

        li   $v0 4		# 印出__txt2_內的東東
	la   $a0 __txt2_
	syscall
        la   $a0 __data_	# call routine (display)(印出排列後data)
        li   $a1 5
	jal  display
 
        li   $v0 10		# 結束syscall
	syscall		   

display:
        addi $sp, $sp, -12	# push registers
        sw   $s2, 0($sp)
        sw   $s3, 4($sp)
        sw   $s4, 8($sp)	
        move $s2, $a0		# 第一筆data的位址
        move $s4, $a1		# 數量
        add  $s3, $0, $0	# for1 (i=0; ; )

for1:   slt  $t0, $s3, $s4	# for1 ( ;i<5; )
        beq  $t0, $0, exit3  
        li   $v0 1		# 印出原始data
        lw   $a0 0($s2)      
        syscall             
        li   $v0 4		# 印出", "
	la   $a0 __xxxx_ 
	syscall
        addi $s2, $s2, 4	# 算出下一個data的位址
        addi $s3, $s3, 1	# for1 ( ; ;i++)
	j    for1

exit3:  lw   $s2, 0($29)	# pop registers
        lw   $s3, 4($29)
        lw   $s4, 8($29)
        addi  $sp, $sp, 12
	jr   $ra		# 回到main

sort: 
      addi $sp, $sp, -20	# push registers
      sw   $ra, 16($sp) 
      sw   $s3, 12($sp)
      sw   $s2, 8($sp)
      sw   $s1, 4($sp)
      sw   $s0, 0($sp)
      move $s2, $a0		# 第一筆data的位址
      move $s3, $a1		# 數量
      move $s0, $zero		# for1tst (j=0; ; )
for1tst:  
	slt $t0, $s0, $s3	# for1tst ( ;j<5; )
	beq $t0, $zero, exit1		# for2tst (k=j-1; ; )
	addi $s1, $s0, -1
for2tst:  
	slti $t0, $s1, 0		# for2tst ( ;k>=0; )
	bne  $t0, $zero, exit2
	add  $t1, $s1, $s1
	add  $t1, $t1, $t1
	add  $s5, $s2, $t1	# $s5=(4*$s1)+$s2
	lw   $t3, 0($s5)
	lw   $t4, 4($s5)
	slt  $t0, $t4, $t3	# if t4<t3 than swap
	beq  $t0, $zero, exit2
	jal  swap
	addi $s1, $s1, -1		# for2tst ( ; ;k--)
	j    for2tst
exit2:    
          addi $s0, $s0, 1	# for1tst ( ; ;j++)
          j    for1tst
exit1:    			# pop registers
          lw   $s0, 0($sp)
          lw   $s1, 4($sp)
          lw   $s2, 8($sp)
          lw   $s3, 12($sp)
          lw   $ra, 16($sp)
          addi $sp, $sp, 20
          jr   $ra		# 回到main

swap:  lw $t0, 0($s5)
       lw $t1, 4($s5)
       sw $t1, 0($s5)
       sw $t0, 4($s5)
       jr $ra

