-
Notifications
You must be signed in to change notification settings - Fork 0
Sorting Using Assembly Language
01sharanshetty edited this page Nov 30, 2023
·
1 revision
#include<stdio.h>
int main(){
int a[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]);
return 0;
}
la $t1, A
addi $s2, $ti, 396
x: add $t2, $t1,4
Y: lw $t3, 0($t1)
lw $t4, 0($t2)
blt $t3, $t4,Z
sw $t3, 0($t2)
sw $t4, 0($t1)
addi $t2, $t2,4
ble $t2 $t2, Y
addi $t1,$t1,4
blt $t1, $s2,x
# Data section
.data
array: .word 2, 1, 4, 3, 6, 5
# Code for sorting the array
.text
main:
# Initialize the loop counter and compare value
li t0, 0 # Initialize the loop counter to 0
li 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 array
add 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 value
slt t4, t3, t1
beq t4, sort_continue # If the current element is greater, continue with the comparison
# Swap the elements
sll t5, t0, 2 # Calculate the address of the element before the current element
sll t6, t0, 4 # Calculate the address of the element after the current element
addi t6, t6, 4 # Calculate the new address of the element after the current element (4-byte alignment)
sw t3, 0(t5) # Store the current element at the address before the current element
sw t3, 0(t6) # Store the compare value at the address after the current element
# Update the loop counter and compare value
addi t0, t0, 1 # Increment the loop counter
srl 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