Home »
Embedded Systems
Sort numbers in ascending order in an array | 8086 Microprocessor
In this tutorial, we will learn how to write an assembly language program in 8086 Microprocessor to sort numbers in ascending order in an array?
By Ayush Sharma Last updated : May 22, 2023
Problem Statement
Write a program in 8086 microprocessor to sort numbers in ascending order in an array of n numbers, where size n is stored at memory address 2000 : 500 and the numbers are stored from memory address 2000 : 501.
Algorithm
- Load data from offset 500 to register CL (for count).
- Travel from starting memory location to last and compare two numbers if first number is greater than second number then swap them.
- First pass fix the position for last number.
- Decrease the count by 1.
- Again travel from starting memory location to (last-1, by help of count) and compare two numbers if first number is greater than second number then swap them.
- Second pass fix the position for last two numbers.
- Repeated.
Program
ADDRESS | MNEMONICS | COMMENTS |
400 | MOV SI, 500 | SI ← 500 |
403 | MOV CL, [SI] | CL ← [SI] |
405 | DEC CL | CL ← CL-1 |
407 | MOV SI, 500 | SI ← 500 |
40A | MOV CH, [SI] | CH ← [SI] |
40C | DEC CH | CH ← CH-1 |
40E | INC SI | SI ← SI+1 |
40F | MOV AL, [SI] | AL ← [SI] |
411 | INC SI | SI ← SI+1 |
412 | CMP AL, [SI] | AL-[SI] |
414 | JC 41C | JUMP TO 41C IF CY=1 |
416 | XCHG AL, [SI] | SWAP AL AND [SI] |
418 | DEC SI | SI ← SI-1 |
419 | XCHG AL, [SI] | SWAP AL AND [SI] |
41B | INC SI | SI ← SI+1 |
41C | DEC CH | CH ← CH-1 |
41E | JNZ 40F | JUMP TO 40F IF ZF=0 |
420 | DEC CL | CL ← CL-1 |
422 | JNZ 407 | JUMP TO 407 IF ZF=0 |
424 | HLT | END |
Explanation
- MOV SI, 500: set the value of SI to 500.
- MOV CL, [SI]: load data from offset SI to register CL.
- DEC CL: decrease value of register CL BY 1.
- MOV SI, 500: set the value of SI to 500.
- MOV CH, [SI]: load data from offset SI to register CH.
- DEC CH: decrease value of register CH BY 1.
- INC SI: increase value of SI BY 1.
- MOV AL, [SI]: load value from offset SI to register AL.
- INC SI: increase value of SI BY 1.
- CMP AL, [SI]: compares value of register AL and [SI] (AL-[SI]).
- JC 41C: jump to address 41C if carry generated.
- XCHG AL, [SI]: exchange the contents of register AL and SI.
- DEC SI: decrease value of SI by 1.
- XCHG AL, [SI]: exchange the contents of register AL and SI.
- INC SI: increase value of SI by 1.
- DEC CH: decrease value of register CH by 1.
- JNZ 40F: jump to address 40F if zero flat reset.
- DEC CL: decrease value of register CL by 1.
- JNZ 407: jump to address 407 if zero flat reset.
- HLT: stop.