On this page
Bubble Sort
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
| |
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
Outer Loop Setup
- CH = 4 (number of passes = n-1)
Inner Loop Setup
- CL = 4 (number of comparisons per pass)
- SI = 2000H (array start address)
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
Move to Next Pair
- INC SI: Move to next element
- DEC CL: Decrease comparison counter
- JNZ INNER: Continue inner loop
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 endPass 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 neededFinal 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:
| |