我正在尝试在汇编程序8051上编写冒泡排序。这是我到目前为止设法完成的操作,它按升序排序,但它也会移动元素,当它完成时在第一个位置留下一个空格。
逐步查看执行情况我注意到SUBB没有改变C的值,使得指令JC SKIP无效。
DEFSEG INICIO1,ABSOLUTE
SEG INICIO1
JMP INICIO
ORG 100H
INICIO: MOV R1,#05H
EXT: MOV A,R1
MOV R2,A
MOV R0,#30H
MOV A,@R0
IN: INC R0
MOV B,@R0
CLR C
SUBB A,B
JC SKIP
MOV B,@R0
DEC R0
MOV A,@R0
MOV @R0,B
INC R0
MOV @R0,A
SKIP: DJNZ R2,IN
DJNZ R1,EXT
STOP: SJMP STOP
JMP FIN
FIN:
END
答案 0 :(得分:0)
在IN
,您需要A
等于@R0
,但在跳转到SKIP
之后,它就不是了!
尝试:
mov r1, #30h
mov @r1, #33h
inc r1
mov @r1, #44h
inc r1
mov @r1, #66h
inc r1
mov @r1, #22h
inc r1
mov @r1, #11h
inc r1
mov @r1, #55h
mov r3, #5
outer:
mov a, r3
mov r2, a
mov r1, #30h
mov a, @r1
inner:
inc r1
clr c
subb a, @r1
mov a, @r1
jc continue
dec r1
xch a, @r1
inc r1
mov @r1, a
continue:
djnz r2, inner
djnz r3, outer
注意到初始计数(5)比要排序的项目数少
。答案 1 :(得分:0)
试试这个子程序
;
; BUBBLE SORT SUBROUTINE DESCRIPTION
; 1. PUSH NO. OF ELEMENT
; 2. PUSH BASE ADDRESS OF ARRAY
;
BUBBLESORT:
POP 0X7F ;RETURN ADDRESS OF SUBROUTINE
POP 0X7E
POP DPH ;BASE ADDRESS OF ARRAY
POP DPL
POP ACC ;COUNTER
PUSH 0X7E ;PUSH RETURN ADDRESS
PUSH 0X7F
MOV R0,A ;TEMPORARY STORE COUNTER REG.
MOV R1,A ;AND BASE ADDRESS OF ARRAY
MOV R2,A
MOV R3,DPL
MOV R4,DPH
REPEAT_BUBBLESORT:
MOVX A,@DPTR ;MOVE A[I] INTO ACCUMULATOR
MOV R5,A
INC DPTR
MOVX A,@DPTR
MOV R6,A
SUBB A,R5
JNC NOTSWAP_BUBBLESORT ;SWAP IF A[I] > A[I+1]
MOV A,R6
XCH A,R5
MOVX @DPTR,A
ACALL DEC_DPTR ;CALL DECREMENT DATA POINTER
MOV A,R5
MOVX @DPTR,A
INC DPTR
NOTSWAP_BUBBLESORT:
DJNZ R2,REPEAT_BUBBLESORT ;LOWER COUNTER
MOV A,R0
MOV R2,A
MOV DPL,R3 ;INITILIZE DPTR WITH BASE ADDRESS
MOV DPH,R4
DJNZ R1,REPEAT_BUBBLESORT ;UPPER COUNTER
RET ;RETURN SUBROUITNE
;DECREMENT DATA POINTER SUBROUITNE
DEC_DPTR:
MOV A,DPL
SUBB A,#01
JNC SKIP_DEC_DPTR
MOV A,#0XFF
DEC DPH
SKIP_DEC_DPTR:
MOV DPL,A
RET
在初始化之前将数组的基地址存储到寄存器中