Sort a list of digits

An array in memory is reached with an index register. Two index registers at once make it possible to compare and swap two elements of the same array, which is the base of every sorting method.

What to build

Read a line of digits and print the same digits in increasing order.

Requirements

  • Store the digits in an array in the data segment.
  • Sort the array with two nested loops that compare elements and swap them with XCHG.
  • Print the sorted digits as one string.

Input

A line of 1 to 9 digits, then Enter.

Output

The digits in increasing order, for example 1235 for 5231.

Constraints

Only digits appear in the line.

Example

Input:

5231

Output:

1235

Why it works

For each position i, the inner loop looks at all the later positions j and swaps whenever the one at j is smaller, so that after the pass the smallest of the rest is at i. After the passes for i = 0, 1, 2, ... the front of the array is complete. Doing this for n − 1 positions sorts the whole array. XCHG with a memory operand swaps in one instruction without a spare register for the second element.

Examples

Example 1 · Input
5231
Expected output
1235
Example 2 · Input
9
Expected output
9

Hints

Hint 1

Store each key in an array: BUF[SI] = AL, then INC SI. When Enter comes, SI is the number of digits; copy it to BX.

Hint 2

Use two indexes: SI = i and DI = j, with j from i + 1 to n − 1. If BUF[i] is above BUF[j], swap them: AL = BUF[SI], XCHG AL, BUF[DI], then BUF[SI] = AL.

Hint 3

The outer loop runs while SI < n − 1. Then print the array from the start, one character at a time.

Solution

Show one correct solution (try it yourself first)
; Sort a list of digits
.MODEL SMALL
.STACK 100H
.DATA
    BUF DB 10 DUP(?)
.CODE
MAIN PROC
    MOV AX, @DATA
    MOV DS, AX
    MOV SI, 0
READ:
    MOV AH, 1
    INT 21H
    CMP AL, 0DH
    JE SORT
    MOV BUF[SI], AL
    INC SI
    JMP READ
SORT:
    MOV BX, SI          ; n
    MOV SI, 0           ; i
OUTER:
    MOV AX, BX
    DEC AX
    CMP SI, AX
    JAE SHOW            ; i reached n - 1
    MOV DI, SI
    INC DI              ; j = i + 1
INNER:
    CMP DI, BX
    JAE NEXTI
    MOV AL, BUF[SI]
    CMP AL, BUF[DI]
    JBE KEEP
    XCHG AL, BUF[DI]    ; swap BUF[i] and BUF[j]
    MOV BUF[SI], AL
KEEP:
    INC DI
    JMP INNER
NEXTI:
    INC SI
    JMP OUTER
SHOW:
    MOV SI, 0
    MOV CX, BX
PRINT:
    MOV DL, BUF[SI]
    MOV AH, 2
    INT 21H
    INC SI
    LOOP PRINT
    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

Lesson: Arrays and addressing modes →