# sort for SPIM based on the code in the text. .data .align 0 space: .asciiz " " lf: .asciiz "\n" before: .asciiz "Before: " after: .asciiz "After: " prompt: .asciiz "Enter Number: " .align 2 array: .word 1,2,5,6,9,0,7,8,3,4 .text # this is program code .align 2 # instructions must be on word boundaries .globl main # main is a global label main: la $a0,array # set up to read in an array of 10 ints li $a1,10 # and put them at label array jal readarray li $v0,4 # print a "Before:" la $a0,before syscall la $a0,array # print out the original array li $a1,10 jal parray la $a0,array # set up for call to sort li $a1,10 jal sort # go sort em li $v0,4 # print "After: " la $a0,after syscall la $a0,array # print the array again (now sorted) li $a1,10 jal parray jr $ra # call the exit system call li $v0,10 syscall # printarray prints an array of integers # called with: # $a0 the address of the array # $a1 the number of elements in the array parray: li $t0,0 # i=0; move $t1,$a0 # t1 is pointer to array pa_loop: beq $t0,$a1,done # done if i==n lw $a0,0($t1) # get a[i] li $v0,1 syscall # print one int li $v0,4 la $a0,space syscall # print a space addi $t1,$t1,4 # update pointer addi $t0,$t0,1 # and count j pa_loop done: li $v0,4 la $a0,lf syscall # print a message addi $sp,$sp,4 jr $ra #------------------------------- # readarray reads in an array of integers # called with: # $a0 the address of the array # $a1 the number of elements in the array readarray: li $t0,0 # i=0; move $t1,$a0 # t1 is pointer to array ra_loop: beq $t0,$a1,ra_done # done if i==n li $v0,4 la $a0,prompt syscall # print one int li $v0,5 syscall sw $v0,0($t1) addi $t1,$t1,4 # update pointer addi $t0,$t0,1 # and count j ra_loop ra_done: li $v0,4 la $a0,lf syscall # print a message addi $sp,$sp,4 jr $ra #------------------------------- sort: addi $sp,$sp,-20 sw $ra, 16($sp) sw $s3, 12($sp) sw $s2, 8($sp) sw $s1, 4($sp) sw $s0, 0($sp) move $s2,$a0 move $s3,$a1 move $s0,$zero for1tst: # move $a0,$s2 # li $a1,10 # jal parray slt $t0,$s0,$s3 beq $t0,$zero,exit1 addi $s1,$s0,-1 for2tst: slti $t0,$s1,0 bne $t0,$zero,exit2 add $t1,$s1,$s1 add $t1,$t1,$t1 add $t2,$s2,$t1 lw $t3,0($t2) lw $t2,4($t2) slt $t0,$t2,$t3 beq $t0,$zero,exit2 move $a0,$s2 move $a1,$s1 jal swap addi $s1,$s1,-1 j for2tst exit2: addi $s0,$s0,1 j for1tst exit1: 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 swap: add $t1,$a1,$a1 add $t1,$t1,$t1 add $t1,$a0,$t1 lw $t0,0($t1) lw $t2,4($t1) sw $t2,0($t1) sw $t0,4($t1) jr $ra