This program implements the bubble sort algorithm to sort an array of bytes in ascending order.

Description

Bubble sort repeatedly steps through the array, compares adjacent elements, and swaps them if they’re in the wrong order. The algorithm continues until no more swaps are needed.

Memory Layout

  • Array starts at address 2000H
  • Array size: 5 elements
  • Elements are sorted in-place

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
MOV CH, 04H ; n-1
OUTER:
	MOV CL , 04H;
    MOV SI, 2000H    

INNER:
    MOV AL, [SI]     
    MOV BL, [SI+1]   
    CMP AL,BL
	JBE SKIP

    XCHG AL, [SI+1]
    MOV [SI], AL

SKIP:
    INC SI
    DEC CL
    JNZ INNER

    DEC CH
    JNZ OUTER

HLT

Explanation

Algorithm Structure

The algorithm uses two nested loops:

  • Outer loop: Runs n-1 times (CH = 4 for 5 elements)
  • Inner loop: Compares adjacent elements (CL = 4 comparisons)

Step-by-Step Process

  1. Outer Loop Setup

    • CH = 4 (number of passes = n-1)
  2. Inner Loop Setup

    • CL = 4 (number of comparisons per pass)
    • SI = 2000H (array start address)
  3. Comparison and Swap

    • MOV AL, [SI]: Load current element
    • MOV BL, [SI+1]: Load next element
    • CMP AL, BL: Compare current with next
    • JBE SKIP: Jump if AL ≤ BL (correct order)
    • XCHG AL, [SI+1]: Swap if out of order
    • MOV [SI], AL: Complete the swap
  4. Move to Next Pair

    • INC SI: Move to next element
    • DEC CL: Decrease comparison counter
    • JNZ INNER: Continue inner loop
  5. Next Pass

    • DEC CH: Decrease pass counter
    • JNZ OUTER: Continue outer loop

Example Execution

Initial Array: [05, 02, 08, 01, 04]

Pass 1:

[05, 02, 08, 01, 04] → Compare 05, 02 → Swap
[02, 05, 08, 01, 04] → Compare 05, 08 → No swap
[02, 05, 08, 01, 04] → Compare 08, 01 → Swap
[02, 05, 01, 08, 04] → Compare 08, 04 → Swap
[02, 05, 01, 04, 08] ← Largest at end

Pass 2:

[02, 05, 01, 04, 08]
[02, 05, 01, 04, 08] → [02, 01, 05, 04, 08]

Pass 3:

[02, 01, 05, 04, 08] → [01, 02, 04, 05, 08]

Pass 4:

[01, 02, 04, 05, 08] → No swaps needed

Final Array: [01, 02, 04, 05, 08]

Time Complexity

  • Best Case: O(n) - already sorted (with optimization)
  • Average Case: O(n²)
  • Worst Case: O(n²) - reverse sorted

Memory Usage

  • In-place sorting (no extra array needed)
  • Space complexity: O(1)

Optimization

To stop early if array is already sorted:

1
2
3
4
; Add a flag to detect if any swap occurred
MOV DH, 00H  ; No swap flag
; Set DH = 01H when swap occurs
; Check DH after inner loop, break if DH = 00H