# Programmer: Mark Fienup # MIPS Insertion sort of an array. # Selection sort High-Level Algorithm # integer firstUnsortedIndex, testIndex, elementToInsert; # # for firstUnsortedIndex = 1 to (length-1) do # testIndex = firstUnsortedIndex-1; # elementToInsert = numbers[firstUnsortedIndex]; # while (testIndex >=0) AND (numbers[testIndex] > elementToInsert ) do # numbers[ testIndex + 1 ] = numbers[ testIndex ]; # testIndex = testIndex - 1; # end while # numbers[ testIndex + 1 ] = elementToInsert; # end for .data numbers: .word 20, 30, 10, 40, 50, 60, 30, 25, 10, 5 length: .word 10 # NOTE: I needed to use "__start" label instead of "main" with the latest version of PCSpim # NOTE: I needed to place the constant 4 in $t7 for the mul instruction with MARS .text .globl __start __start: # Register usage: Since I'm not calling an subprograms, I don't # really need to follow and register convensions, but I'll try to # use only temporary register ($t#). This would make it easier to # convert to a subprogram later. # $t0 = value of (length-1) # $t1 = firstUnsortedIndex # $t2 = testIndex # $t3 = elementToInsert # $t4 = address of element numbers[] # $t5 = base address of numbers # $t6 = value of numbers[testIndex] # $t7 = value of 4 (so it will run in MARS) for: la $t5, numbers lw $t0, length addi $t0, $t0, -1 li $t1, 1 li $t7, 4 for_compare: bgt $t1, $t0, end_for addi $t2, $t1, -1 mul $t4, $t1, $t7 add $t4, $t5, $t4 lw $t3, 0($t4) while: blt $t2, 0, end_while mul $t4, $t2, $t7 add $t4, $t4, $t5 lw $t6, 0($t4) ble $t6, $t3, end_while sw $t6, 4($t4) addi $t2, $t2, -1 j while end_while: mul $t4, $t2, $t7 add $t4, $t5, $t4 sw $t3, 4($t4) addi $t1, $t1, 1 j for_compare end_for: li $v0, 10 # exit system call syscall endMain: