You are on page 1of 1

1 VD: SORT

2 ; Implementing bubble sort algorithm


3 ; R0 File item
4 ; R1 File item
5 ; R2 Work variable
6 ; R3 File pointer
7 ; R4 Outer loop counter
8 ; R5 Inner loop counter
9
10 .ORIG x3000 ; Count the number of items to be sorted and
11 store the value in R7
12 AND R2, R2, #0 ; Initialize R2 <- 0 (counter)
13 LD R3, FILE ; Put file pointer into R3
14 COUNT LDR R0, R3, #0 ; Put next file item into R0
15 BRZ END_COUNT ; Loop until file item is 0
16 ADD R3, R3, #1 ; Increment file pointer
17 ADD R2, R2, #1 ; Increment counter
18 BRNZP COUNT ; Counter loop
19 END_COUNT ADD R4, R2, #0 ; Store total items in R4 (outer loop count)
20 BRZ SORTED ; Empty file
21
22 ; Do the bubble sort
23
24 OUTERLOOP ADD R4, R4, #-1 ; loop n - 1 times
25 BRNZ SORTED ; Looping complete, exit
26 ADD R5, R4, #0 ; Initialize inner loop counter to outer
27 LD R3, FILE ; Set file pointer to beginning of file
28 INNERLOOP LDR R0, R3, #0 ; Get item at file pointer
29 LDR R1, R3, #1 ; Get next item
30 NOT R2, R1 ; Negate ...
31 ADD R2, R2, #1 ; ... next item
32 ADD R2, R0, R2 ; swap = item - next item
33 BRNZ SWAPPED ; Don't swap if in order (item <= next item)
34 STR R1, R3, #0 ; Perform ...
35 STR R0, R3, #1 ; ... swap
36 SWAPPED ADD R3, R3, #1 ; Increment file pointer
37 ADD R5, R5, #-1 ; Decrement inner loop counter
38 BRP INNERLOOP ; End of inner loop
39 BRNZP OUTERLOOP ; End of outer loop
40 SORTED HALT
41
42 FILE .FILL x3500 ; File location
43 .END
44

You might also like