[MIPS] The goal here is to rewrite C code into MIPS. Please dont use any convert
ID: 3802210 • Letter: #
Question
[MIPS] The goal here is to rewrite C code into MIPS. Please dont use any converters as it is obvious and uneducational.
#include <stdio.h>
void bubbleSort(int *num, int size)
{
int j;
int flag = 1; //set flag to true to begin first pass.
int temp; //holding variable.
while(flag)
{
flag = 0; //set flag to false awaiting a possible swap.
for(j = 0; j < size-1; j++)
{
if(*(num+j) < *(num+j+1)) //change to > for ascending sort
{
temp = *(num+j); //swap elements.
*(num+j) = *(num+j+1);
*(num+j+1) = temp;
flag = 1; //shows a swap occurred.
}
}
}
}
int main()
{
int array[] = {99, 88, 66, 77, 44, 55, 11, 33, 22};
printf("Before Sorting: ");
for(int i = 0; i < 9; i++)
printf("%d ", array[i]);
printf(" ");
bubbleSort(array, 9);
printf("After Sorting: ");
for(int i = 0; i < 9; i++)
printf("%d ", array[i]);
printf(" ");
}
Explanation / Answer
.data
array: .word 99,88,66,77,44,55,11,33,22
str1: .asciiz "array before sorting "
str2: .asciiz "array after sorting "
count: .word 9
.text
.global main
main: li $a2,9 #loading a2 with 9
li $t0,0 #loading zero to $t0
la $t0,array #here $t0 stores base address of array
addi $t4,$to,36 #writing t4 with last address of array
li $a1,0 #loading zero to $a1
la $a0,str1 #printing str1
li $v0,4
syscall
#printing array values before sorting
mo1: lw $a0, ($t0)
li $v0,1
syscall
addi $t0,$t0,4
bne $t0,$t4,mo1
jal sorting #calling sorting function
la $a0,str2 #printing str2
li $v0,4
syscall
#printing array values after sorting
la $t0,array
mo2: lw $a0, ($t0)
li $v0,1
syscall
addi $t0,$t0,4
bne $t0,$t4,mo2
sorting:
loop1: la $t0,array #here $t0 stores base address of array
li $t1, 0 #using $t1 as flag for swapping
loop2: lw $t2,0($t0) #loading one value of array to $t2
lw $t3,4($t0) #loading next value of array to $t3
slt $t1,$t2,$t3 #setting flag $t1=1 if $t2<$t3
blez $t1,next #if flag is not set skipping sorting
sw $t2,4($t0) #sorting
sw $t3,0($t0)
next:
addi $t0,$t0,1 #moving to next value of array
addi $a1,$a1,1 #incrementing value
bne $a1,$a2,loop2 #if the total values in array are sorted for one time then stop loop2
bne $t1,$0,loop1 #if flag set after last sort the continue sorting again
jr $ra #returning to main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.