650610155 BUBLE SORT HW

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

;

; Basic assembly programming


; Data Sorting(maximum value in high address)
;
; Data_space_address input_data(Unsigned Int) output_data(Unsigned Int)
; 0x0100 0xFF
0x01
; 0x0101 0x03
0x02
; 0x0102 0x02
0x03
; 0x0103 0x04
0x04
; 0x0104 0x01
0xFF
;
.org 0x0000
JMP START
;--------------------------------------------
START:

LDI R26,0x00 ; Initialize the X pointer (lower byte)


LDI R27,0x01 ; Initialize the X pointer (higher byte)

LDI R17,0x00 ; Initialize array size variable

LDI R16,0xFF ;load data to GPR


ST X+, r16 ; store in SRAM (the first member of array)
INC R17 ; increase array size when add array member

LDI R16,0x03
ST X+, r16
INC R17

LDI R16,0x02
ST X+, r16
INC R17

LDI R16,0x04
ST X+, r16
INC R17

LDI R16,0x01
ST X+, r16 ; store in SRAM (the last member of array)
INC R17

call BUBBLE_SORT
;--------------------------------------------
END: jmp END

;====================================================
;input SRAM ADDR 0x100 to 0x104, R17 (array size variable)
;output SRAM ADDR 0x100 to 0x104
;resource R18, R19, R20, R26, R27

BUBBLE_SORT:
MOV R18, R17 ; Outer loop counter initialization
DEC R18 ; R18 = array size - 1 (since we compare pairs)
OUTER_LOOP:
MOV R19, R18 ; Copy outer loop counter to inner loop counter

LDI R26, 0x00 ; Reinitialize X pointer (lower byte)


LDI R27, 0x01 ; Reinitialize X pointer (higher byte)

INNER_LOOP:
LD R0, X ; Load value at current position
LD R1, X+ ; Load next value

CP R0, R1 ; Compare R0 with R1


BRLO NO_SWAP ; If R0 < R1, no need to swap

MOV R20, R0 ; Swap: Store R0 in R20


ST -X, R1 ; Store R1 back in the previous position
ST X+, R20 ; Store R0 in the next position

NO_SWAP:
DEC R19 ; Decrement inner loop counter
BRNE INNER_LOOP ; If not zero, repeat inner loop

DEC R18 ; Decrement outer loop counter


BRNE OUTER_LOOP ; If not zero, repeat outer loop

RET ; Finish, return to the called function

;====================================================

You might also like