 # Bubble Sort (Assembly)

Sep 18th, 2021
984
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. .model small
2. .stack 100h
3.
4. .data
5. arr     db 20 dup(?)
6. n       dw ?
7. i       dw ?
8. j       dw ?
9. msg_1   db "Enter number of elements: \$"
10. msg_2   db "Enter numbers (0-9): \$"
11. msg_3   db "After sorting: \$"
12. endl    db 0ah,0dh,"\$"
13.
14. .code
15. main proc
16.     mov ax, @data
17.     mov ds, ax
18.
19.     mov ah, 9
20.     lea dx, msg_1
21.     int 21h
22.
23.     mov ah, 1
24.     int 21h
25.     sub al, 48
26.     mov ah, 0
27.     mov n, ax   ;storing total number of elements
28.
29.     mov ah, 9
30.     lea dx, endl
31.     int 21h
32.     lea dx, msg_2
33.     int 21h
34.
35.     lea SI, arr ; SI contains the offset of arr
36.     mov cx, n   ; cx = n
37.
38.     ; taking the input of n elements
39.     INPUT:
40.     mov ah, 1
41.     int 21h
42.     sub al, 48
43.     mov [SI], al ; store input in arr
44.     inc SI  ; point SI to the next index
45.
46.     mov ah, 2
47.     mov dl, ' ' ; printing space between consecutive elements
48.     int 21h
49.     loop INPUT
50.
51.     lea SI, arr ; SI contains the offset of arr
52.     mov bx, n   ; bx = n
53.     call bubble_sort
54.
55.     mov ah, 9
56.     lea dx, endl
57.     int 21h
58.     lea dx, msg_3
59.     int 21h
60.
61.     lea SI, arr ; SI contains the offset of arr
62.     mov cx, n
63.
64.     PRINT:  ; print the array
65.     mov ah, 2
66.     mov dl, [SI]
68.     int 21h
69.     mov dl, ' '
70.     int 21h
71.     inc SI
72.     loop PRINT
73.
74.     mov ah, 4ch
75.     int 21h
76.
77.     main endp
78.
79. bubble_sort proc
80.     ;push the passed parameter in stack to store their value
81.     push bx
82.     push SI
83.
84.     mov DX, SI ; storing offset address saved in SI into DX, means DX = SI
85.
86.     mov i, 1
87.     OUTER:
88.     cmp i, bx ; as bx = n
89.     jge EXIT
90.
91.     inc i
92.     mov j, 1
93.
94.     mov SI, DX  ; as DX = SI
95.     mov DI, SI  ; DI = SI
96.     inc SI ; SI becomes 1 step ahead of DI
97.
98.     INNER:
99.     cmp j, bx
100.     jge OUTER
101.
102.     mov al, [SI] ; al -> arr[j]
103.     cmp al, [DI] ; [DI] -> arr[j-1]
104.     jl swap
105.     inc j
106.     inc SI ; increment both SI and DI
107.     inc DI
108.     jmp INNER
109.
110.     swap:
111.     mov al, [SI]    ; al = arr[j]
112.     xchg al, [DI]   ; [DI] = al and al = [DI]
113.     mov [SI], al    ; arr[j] = al
114.     inc j
115.     inc SI ; increment both SI and DI
116.     inc DI
117.     jmp INNER
118.
119.     EXIT:
120.
121.     pop SI ; restore passed parameter value before function returns
122.     pop BX
123.
124.     ret
125.
126.     bubble_sort endp
127. end main
RAW Paste Data