Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.MODEL SMALL
.DATA
NUMBERS DB 4 DUP (?)
J DW 1
I DW ?
LINEBREAK DB 10, 13, "$"
KEY DB ?
MSG1 DB "Ascending Order: $"
MSG2 DB "Descending Order: $"
.CODE
MOV AX, @DATA
MOV DS, AX
; take input of 4 numbers
MOV CX, 4
MOV AH, 1
LEA SI, NUMBERS
L1:
INT 21h
MOV [SI], AL
INC SI
LOOP L1
; line break
MOV AH, 9
LEA DX, LINEBREAK
INT 21h
; sort the numbers
MOV CX, 3
L3:
; key = A[j]
LEA SI, NUMBERS
ADD SI, J
MOV BH, [SI]
MOV KEY, BH
; i = j - 1
MOV DX, J
MOV I, DX
DEC I
PREPREWHILE:
; i > 0
CMP I, 0
JGE PREWHILE
JNGE AFTERWHILE
PREWHILE:
; A[i] => BH
LEA SI, NUMBERS
ADD SI, I
MOV BH, [SI]
; A[i] > key
CMP BH, KEY
JG WHILE
JNG AFTERWHILE
WHILE:
; A[i] => BH
LEA SI, NUMBERS
ADD SI, I
MOV BH, [SI]
; A[i + 1] = A[i]
LEA SI, NUMBERS
ADD SI, I
INC SI
MOV [SI], BH
DEC I
JMP PREPREWHILE
AFTERWHILE:
; A[i + 1] = key
LEA SI, NUMBERS
ADD SI, I
INC SI
MOV BH, KEY
MOV [SI], BH
INC J
LOOP L3
; ascending order
MOV AH, 9
LEA DX, MSG1
INT 21h
MOV CX, 4
LEA SI, NUMBERS
MOV AH, 2
L2:
MOV DL, [SI]
INT 21h
INC SI
LOOP L2
; line break
MOV AH, 9
LEA DX, LINEBREAK
INT 21h
; descending order
MOV AH, 9
LEA DX, MSG2
INT 21h
MOV CX, 4
LEA SI, NUMBERS
ADD SI, CX
MOV AH, 2
L4:
DEC SI
MOV DL, [SI]
INT 21h
LOOP L4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment