Skip to content

Commit 747b34e

Browse files
authored
Assembly Bubblesort
1 parent c38aadb commit 747b34e

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

Assembly/bubblesort.asm

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# bubbleSort.asm
2+
3+
# SETUP
4+
.data
5+
#set the size and content of array
6+
#Sz: .word 50
7+
Sz: .word 100
8+
Array: 7, 5, 4, 1, 6, 8, 3, 2, 9, 0, 8, 3, 2, 4, 9, 0, 6, 7, 5, 1, 1, 6, 5, 7, 4, 8, 2, 3, 9, 0, 2, 8, 5, 1, 3, 9, 6, 0, 7, 4, 5, 8, 1, 6, 0, 7, 9, 2, 3, 4, 7, 9, 0, 2, 5, 1, 8, 6, 3, 4, 2, 8, 4, 5, 0, 7, 3, 9, 6, 1, 2, 0, 3, 6, 5, 4, 7, 9, 1, 8, 5, 6, 8, 1, 3, 2, 0, 9, 7, 4, 9, 3, 2, 1, 7, 5, 6, 8, 0, 4
9+
10+
NL: .asciiz "\n"
11+
.text
12+
# Initialize List
13+
main:
14+
lw $s7, Sz # get size of list
15+
move $s1, $zero # set counter for # of elems printed
16+
move $s2, $zero # set offset from Array
17+
18+
#program in C:
19+
# for (int k = 1; k < size; k++){
20+
# for (int i = 0; i <size - k; i++){
21+
# if (a[i] > a[i +1]){
22+
# int temp = a[i];
23+
# a[i + 1] = temp;
24+
# }
25+
# }
26+
# }
27+
28+
#Variable meanings:
29+
#t0; k
30+
#t1: i
31+
#t2: a[i]
32+
#t3: a[i+1]
33+
#t4: size - k
34+
#t5: temp
35+
#s3: [i+1]
36+
37+
# sort the list:
38+
outer_loop:
39+
beq $t0, $s7, end_of_sort #end loop if counter reached size of array
40+
addi $t1, $zero, 0 #reset inner loop counter
41+
inner_loop:
42+
sub $t4, $s7, $t0 #store the values of size - k for comparison later
43+
beq $t1, $t4, end_of_inner_loop #end inner loop if counter reached comparitor values
44+
mul $s2, $t1, 4
45+
lw $t2, Array($s2) #load a[i]
46+
addi $s3, $s2, 4
47+
lw $t3, Array($s3) #load a[i+1]
48+
49+
ble $t2, $t3, after_swap
50+
51+
move $t5, $t2 #store a[i] in temp
52+
move $t2, $t3 #swap
53+
move $t3, $t5
54+
55+
sw $t2, Array($s2)
56+
sw $t3, Array($s3)
57+
after_swap:
58+
59+
addi $t1, $t1, 1 #increment inner counter
60+
j inner_loop #jump to start of inner
61+
62+
end_of_inner_loop:
63+
addi $t0, $t0, 1 #increment outer counter
64+
j outer_loop #jump to start of outer
65+
66+
end_of_sort:
67+
# main print loop
68+
move $s1, $zero # set counter for # of elems printed
69+
move $s2, $zero # set offset from Array
70+
71+
print_loop:
72+
bge $s1, $s7, print_loop_end # stop after last elem is printed
73+
lw $a0, Array($s2) # print next value from the list
74+
li $v0, 1
75+
syscall
76+
la $a0, NL # print a newline
77+
li $v0, 4
78+
syscall
79+
addi $s1, $s1, 1 # increment the loop counter
80+
addi $s2, $s2, 4 # step to the next array elem
81+
82+
j print_loop # repeat the loop
83+
print_loop_end:

0 commit comments

Comments
 (0)