Comparing and jumping lets a program put values in order. For three values, three compare and swap steps are enough.
What to build
Read three digits and print them in increasing order.
Requirements
- Put the digits in three registers.
- Use CMP, a conditional jump and XCHG to sort them in place.
- Print the digits as one string without spaces.
Input
Three digits, then Enter.
Output
The same digits in increasing order, for example 159 for 915.
Constraints
Each of the three characters is a digit from 0 to 9. Equal digits are allowed.
Example
Input:
915
Output:
159
Why it works
The first step moves the largest of the first two to the middle, the second step moves the largest of all three to the end, and then the first two are in the wrong order at most once more, which the third step fixes. The jump uses JBE, so equal digits are not swapped.
Examples
915
159
123
123
Hints
Hint 1
Read the three digits into BL, BH and CL. Compare characters: they have the same order as the digits.
Hint 2
Sorting three values takes three compare-and-swap steps: (BL, BH), then (BH, CL), then (BL, BH) again.
Hint 3
A compare-and-swap is CMP BL, BH, then JBE past an XCHG BL, BH.
Solution
Show one correct solution (try it yourself first)
; Sort three digits
.MODEL SMALL
.STACK 100H
.CODE
MAIN PROC
MOV AH, 1
INT 21H
MOV BL, AL
INT 21H
MOV BH, AL
INT 21H
MOV CL, AL
CMP BL, BH
JBE STEP2
XCHG BL, BH
STEP2:
CMP BH, CL
JBE STEP3
XCHG BH, CL
STEP3:
CMP BL, BH
JBE SHOW
XCHG BL, BH
SHOW:
MOV AH, 2
MOV DL, BL
INT 21H
MOV DL, BH
INT 21H
MOV DL, CL
INT 21H
MOV AH, 4CH
INT 21H
MAIN ENDP
END MAIN
▶ Open this solution in the compiler, then press Visualize to watch it run step by step