Saturday, April 30, 2016

8051 Program – sorting descending order

; descending order sorting an array of n element
; compare value at n with n+1th location
; exchange value at n+1th is larger than nth
; repeat the same for n-1 times for n-1 iteration
; array: 4000H - 4004H
;result: 4000H - 4004H
ORG 0H
ARRAY_ADDR EQU 4000H
ELEMENT_COUNT EQU 5
MAIN:
MOV DPTR,#ARRAY_ADDR ; fill memory
MOV A, #05H
MOVX @DPTR,A
INC DPTR
MOV A, #08H
MOVX @DPTR,A
INC DPTR
MOV A, #07H
MOVX @DPTR,A
INC DPTR
MOV A, #06H
MOVX @DPTR,A
INC DPTR
MOV A, #04H
MOVX @DPTR,A
LCALL SORT
SJMP MAIN
SORT:
MOV R0,#ELEMENT_COUNT ; outer loop
loop:MOV R1,#ELEMENT_COUNT ; inner loop
DEC R1
MOV DPTR,#ARRAY_ADDR
loop1: PUSH DPH
PUSH DPL
MOVX A,@DPTR
MOV B,A
INC DPTR
MOVX A,@DPTR
CJNE A,B,loop2
loop2: JC loop3
POP DPL ; exchange n with n+1
POP DPH
MOVX @DPTR,A
INC DPTR
MOV A,B
MOVX @DPTR,A
AJMP loop4
loop3: POP DPL
POP DPH
INC DPTR
loop4: DJNZ R1,loop1 ; repeat for next location
DJNZ R0,loop ; next iteration
RET
END



Related topics:
8051 Program - sorting ascending order   |   8051 Program - bubble sort ascending order   |   8051 Program - bubble sort descending order   |   8051 Program - pwm   |   8051 Program - decimal to hex   |   8051 Program - sum of a set of numbers   |   8051 Program - memory subroutines   |   8051 Program - math subroutines   |   8051 Program - conversion subroutines

List of topics: 8051

No comments:

Post a Comment