i'm learning Assembly on Motorola 68k, i was able to do BubbleSort in ascending order but not descending, i don't know why the program goes into infinite loop; Thx;: The code:
ORG $2000
START LEA ARRAY,A0
CLR D0 *Flag di scambio
MOVE.B #L-1,D1 *contatore
LOOP MOVE.B (A0),D2
MOVE.B 1(A0),D3
CMP D2,D3
BLE ELSE
MOVE.B D2,1(A0)
MOVE.B D3,(A0)
MOVE.B #1,D0
ELSE ADD #1,A0
DBRA D1,LOOP
TST D0
BNE START
SIMHALT
ORG $1000
ARRAY DC.B 1,5,2,4,3
L EQU 5
END START
MOVE.B #L-1,D1 *contatore
LOOP MOVE.B (A0),D2
MOVE.B 1(A0),D3
CMP D2,D3
BLE ELSE
MOVE.B D2,1(A0)
MOVE.B D3,(A0)
MOVE.B #1,D0
ELSE ADD #1,A0
DBRA D1,LOOP
Your loop that is based on the D1
contatore runs for too long, In an array that has 5 elements. you can do at most 4 comparisons. That's why you wrote #L-1
. However the DBRA
instruction repeats until the count is -1 , so in this case you still get 5 iterations which is 1 too many.
i don't know why the program goes into infinite loop;
An infinite loop could result from not having initialized the whole 16-bit counter for the DBRA D1,LOOP
instruction! Better use MOVE.W #L-1,D1
.
When the non-zero D0
register tells you that a change was made to the array, you repeat the whole code. That can work ok, but it is more efficient to realize that the smallest element will have bubbled to the far end and need not be processed any more. The solution is to have a variable contatore instead of the constant #L-2
(after correction).
START MOVE.W #L-2,D4 *first_contatore
NEXT LEA ARRAY,A0
CLR D0 *Flag di scambio
MOVE.W D4,D1 *contatore
LOOP ...
...
DBRA D1,LOOP
TST.B D0
BEQ DONE *Nothing was changed, earliest exit
DBRA D4,NEXT
DONE SIMHALT
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.