Assembly Code Example: Selection Sort
Assembly Code Example: Selection Sort
Selection Sort
Swap Function in C
jr $ra
Selection Sort function in C
void SelSort(int v[], int length)
{
int indexMin;
for(int s = 0; s < length-1; s++){
indexMin = s;
for(int k = s+1; k < length; k++){
if(v[k] < v[indexMin])
indexMin = k;
}
swap(v[s], v[indexMin]);
}
}
Selection Sort in Assembly Code
• Do we make a subsidiary function call?
– Yes, must save state, use s registers
• What must go into s registers?
– Variables whose values must be retained across
function calls
• v base, length, length-1, s
– Other variables can use t registers
• k, minIndex, temps for address/branch computations
• Construct code by units (if, for, for)
Selection Sort in Assembly Code
# register assignments
# v base in $s0 (move from $a0)
# length in $s1 (move from $a1)
# length-1 in $s2 (compute from n)
# s in $s3 (initialize to 0)
# minIndex in $t0
# k in $t1
Selection Sort in Assembly Code
# if(v[k] < v[minIndex]) { minIndex = k }
#
sll $t3, $t1, 2 # t3 = 4 * k
add $t3, $s0, $t3 # t3 = address of v[k]
sll $t4, $t0, 2 # t4 = 4 * minIndex
add $t4, $s0, $t4 # t4 = addr of v[minIndex]
lw $t5, 0($t3) # t5 = v[k]
lw $t6, 0($t4) # t6 = v[minIndex]
# { if…}