Sorting Using Assembly Language - muneeb-mbytes/computerArchitectureCourse GitHub Wiki
Sorting using C language
#include<stdio.h>intmain(){
inta[50], i,j,n,t;
printf("enter the No: of elements in the list:");
scanf("%d", &n);
printf("enter the elements:");
for(i=0; i<n; i++){
scanf ("%d", &a[i]);
}
printf("Before bubble sorting the elements are:");
for(i=0; i<n; i++)
printf("%d \t", a[i]);
for (i=0; i<n-1; i++){
for (j=i+1; j<n; j++){
if (a[i] >a[j]){
t=a[i];
a[i] =a[j];
a[j] =t;
}
}
}
printf ("after bubble sorting the elements are:");
for (i=0; i<n; i++)
printf("%d\t", a[i]);
return0;
}
# Data section.dataarray: .word 2,1,4,3,6,5# Code for sorting the array.textmain:# Initialize the loop counter and compare valueli t0,0 # Initialize the loop counter to 0li t1,5 # Initialize the compare value to 5 (array length -1)sort_loop:sll t2, t1,2 # Calculate the current element's address in the arrayadd t2, t2,4 # Calculate the current element's address in the array (4-byte alignment)lw t3,0(t2) # Load the current element into a register# Check if the current element is greater than the compare valueslt t4, t3, t1beq t4, sort_continue # If the current element is greater, continue with the comparison# Swap the elementssll t5, t0,2 # Calculate the address of the element before the current elementsll t6, t0,4 # Calculate the address of the element after the current elementaddi t6, t6,4 # Calculate the new address of the element after the current element (4-byte alignment)sw t3,0(t5) # Store the current elementatthe address before the current elementsw t3,0(t6) # Store the compare valueatthe address after the current element# Update the loop counter and compare valueaddi t0, t0,1 # Increment the loop countersrl t1, t1,31 # Shift the loop counter to the right by 31 bits (to sign-extend)bgez t1, sort_loop # If the loop counter is non-negative, continue the loop