# Programmer: Mark Fienup # MIPS Insertion sort of an array BY WALKING A POINTER THROUGH THE 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 = ADDRESS of numbers[length-1], i.e., addr. of last element in array # $t1 = ADDRESS of numbers[firstUnsortedIndex] # $t3 = elementToInsert # $t4 = ADDRESS of numbers[testIndex] # $t5 = base address of numbers # $t6 = value of numbers[testIndex] # $t7 = value of 4 (so it will run in MARS) for: li $t7, 4 la $t5, numbers lw $t0, length addi $t0, $t0, -1 mul $t0, $t0, $t7 # calc. address of numbers[length-1] add $t0, $t5, $t0 addi $t1, $t5, 4 # initialize $t1 to addr. of numbers[1] for_compare: bgt $t1, $t0, end_for # if firstUnsorted runs off right end of array, stop addi $t4, $t1, -4 # initialize address of numbers[testIndex] lw $t3, 0($t1) while: blt $t4, $t5, end_while # if addr. of numbers[testIndex] runs off left end of array, stop lw $t6, 0($t4) ble $t6, $t3, end_while sw $t6, 4($t4) addi $t4, $t4, -4 # walk addr. of numbers[testIndex] to addr. of numbers[testIndex-1] j while end_while: sw $t3, 4($t4) addi $t1, $t1, 4 # walk addrs. of numbers[firstUnsortedIndex] to next element j for_compare end_for: li $v0, 10 # exit system call syscall endMain: