Write a MIPS assembly program that sorts data in the descending order (from the
ID: 3598091 • Letter: W
Question
Write a MIPS assembly program that sorts data in the descending order (from the biggest to the smallest) using any sorting algorithm. The input data is defined in the data section (Input_data). Output_data are initially filled with 0s, as shown below. After executing your sorting program, Output_data in the data section should have the sorted numbers from the biggest to the smallest (from +15 to -16). All 32 input numbers should be sorted in the descending order. Screen-capture the execution outcome in SPIM. Explain your algorithm to sort the data. Note that you should add comments beside each line of your assembly code.
.data
.align 4
Input_data: .word 2, 0, -7, -1, 3, 8, -4, 10
.word -9, -16, 15, 13, 1, 4, -3, 14
.word -8, -10, -15, 6, -13, -5, 9, 12
.word -11, -14, -6, 11, 5, 7, -2, -12
Output_data: .word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
.word 0, 0, 0, 0, 0, 0, 0, 0
Explanation / Answer
.data
.align 4
Input_data: .word 2, 0, -7, -1, 3, 8, -4, 10
.text
.globl main
main:
la $t0, Input_data // Copy the base address of your array into $t1
add $t0, $t0, 40 // 4 bytes per int * 10 ints = 40 bytes
outterLoop: // Used to determine when we are done iterating over the Array
add $t1, $0, $0 // $t1 holds a flag to determine when the list is sorted
la $a0, Input_data // Set $a0 to the base address of the Array
innerLoop: // The inner loop will iterate over the Array checking if a swap is needed
lw $t2, 0($a0) // sets $t0 to the current element in array
lw $t3, 4($a0) // sets $t1 to the next element in array
slt $t5, $t2, $t3 // $t5 = 1 if $t0 < $t1
beq $t5, $1, continue // if $t5 = 1, then swap them
add $t1, $0, 1 // if we need to swap, we need to check the list again
sw $t2, 4($a0) // store the greater numbers contents in the lower position in array (swap)
sw $t3, 0($a0) // store the lesser numbers contents in the higher position in array (swap)
continue:
addi $a0, $a0, 4 // advance the array to start at the next location from last time
bne $a0, $t0, innerLoop // If $a0 != the end of Array, jump back to innerLoop
bne $t1, $0, outterLoop // $t1 = 1, another pass is needed, jump back to outterLoop
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.