The Insertion sort is a sorting algorithm where each iteration of the "main" loop extends the size of the sorted part by one element. The idea is to extend the sorted part by inserting the first unsorted element into the correct spot in the sorted part. In the below example, 35 should be inserted between 30 and 40 in the sorted part. To do this, you must find the correct spot to insert 35 and shift larger elements (40 and 50) to the right one location to make room for 35. The following algorithm calls a subprogram Insert which combines finding the insertion spot and shifting larger elements as follows:

The following example show these steps:

Reg.

#

Convention Name Role in Procedure Calls Comments
$0 $zero value zero  
$1 $at Used by assembler to implement psuedoinstructions DON'T USE
$2, $3 $v0, $v1 Results of a function  
$4 - $7 $a0 - $a3 First 4 arguments to a procedure  
$8 - $15,

$24, $25

$t0 - $t9 Temporary registers (not preserved across call) Caller-saved registers - subprogram can use them as scratch registers, but it must also save any needed values before calling another subprogram.
$16 - $23 $s0 - $s7 Saved temporary (preserved across call) Callee-saved registers - it can rely on an subprogram it calls not to change them (so a subprogram wishing to use these registers must save them on entry and restore them before it exits)
$26, $27 $k0, $k1 Reserved for the Operating System Kernel DON'T USE
$28 $gp Pointer to global area  
$29 $sp Stack pointer Points to first free memory location above stack
$30 $fp/$s8 Frame pointer (if needed) or another saved register $fp not used so use as $s8
$31 $ra Return address (used by a procedure call) Receives return addr. on jal call to procedure

Implement the following two Insertion sort subprograms (i.e., InsertionSort and Insert) using the MIPS register conventions. Include all assembly language directives (.data, .text, etc.) to make a complete program. For each subprogram, include comments indicating what argument or local variable each register is holding.

(Note: "length" argument to InsertionSort is a count of elements in the array "numbers")

InsertionSort(numbers - address to integer array, length - integer)

integer firstUnsortedIndex

for firstUnsortedIndex = 1 to (length-1) do

Insert(numbers, numbers[firstUnsortedIndex], firstUnsortedIndex-1);


end for
end InsertionSort

Insert(numbers - address to integer array, elementToInsert - integer, firstSortedIndex - integer) {

integer testIndex;

testIndex = firstSortedIndex;

while (testIndex >=0) AND (numbers[testIndex] > elementToInsert ) do

numbers[ testIndex + 1 ] = numbers[ testIndex ];

testIndex = testIndex - 1;
end while

numbers[ testIndex + 1 ] = elementToInsert;
end Insert