Sem 6‎ > ‎MPRC LAB‎ > ‎

P7: Sort in ascending and descending order

posted Apr 7, 2013, 2:13 AM by Neil Mathew   [ updated Apr 7, 2013, 3:20 AM by Neil Mathew ]

Bubble sort.

This pic should help. Two loops are there in a bubble sort. One inner loop to go through the elements and push the largest number to the end (while the other numbers like bubbles float towards the top) and the Outer loop which reduce the set of numbers, removing the last largest number from the set.



Four Registers required:

A is used as a temporary register while traversing the series.
B is used as a temporary register to swap numbers.
C is used as the iterator for the outer loop
D is used as the iterator for the inner loop



Program:

LXI H, 2500 (count) (n)
MOV C, M n-1 comparisons
DCR C
OUTERLOOP MOV D, C
LXI H, 2501 (1st of series)
INNERLOOP MOV A, M
INX H
CMP M
JC AHEAD A < B => Carry => ASC Order

if No Carry, Not ASC, 
Swap.
MOV B, M START SWAP STTMENTS:
MOV M, A
DCX H
MOV M, B
INX H END SWAP STTMENTS
DCR D
JNZ INNERLOOP
DCR C
JNZ OUTERLOOP
RST1




FOR DESCENDING ORDER, USE JNC in place of JC.



LXI H, 2500(count) (n)
MOV C, Mn-1 comparisons
DCR C
OUTERLOOPMOV D, C
LXI H, 2501(1st of series)
INNERLOOPMOV A, M
INX H
CMP M
JNC AHEADA < B => Carry.

if Carry, Swap
=> DESC Order
MOV B, MSTART SWAP STTMENTS:
MOV M, A
DCX H
MOV M, B
INX HEND SWAP STTMENTS
DCR D
JNZ INNERLOOP
DCR C
JNZ OUTERLOOP
RST1




Comments