š Bubble Sort Algorithm with Playing Cards
Initial Array
Starting with our unsorted cards
Pass 1, Step 1: Compare 5 and 2
5 > 2, so we need to swap them
5 > 2 ā SWAP
Pass 1, Step 2: Compare 5 and 8
5 < 8, so no swap needed
5 < 8 ā NO SWAP
Pass 1, Step 3: Compare 8 and 3
8 > 3, so we need to swap them
8 > 3 ā SWAP
Pass 1, Step 4: Compare 8 and 6
8 > 6, so we need to swap them
8 > 6 ā SWAP
ā
8 is now in its final position!
Pass 2, Step 1: Compare 2 and 5
2 < 5, so no swap needed
2 < 5 ā NO SWAP
Pass 2, Step 2: Compare 5 and 3
5 > 3, so we need to swap them
5 > 3 ā SWAP
Pass 2, Step 3: Compare 5 and 6
5 < 6, so no swap needed
5 < 6 ā NO SWAP
ā
6 is now in its final position!
Pass 3, Step 1: Compare 2 and 3
2 < 3, so no swap needed
2 < 3 ā NO SWAP
Pass 3, Step 2: Compare 3 and 5
3 < 5, so no swap needed
3 < 5 ā NO SWAP
ā
5 is now in its final position!
Pass 4, Step 1: Compare 2 and 3
2 < 3, so no swap needed
2 < 3 ā NO SWAP
ā
3 is now in its final position!
š Final Sorted Array
All cards are now in ascending order!
ā
Bubble sort complete! The array is fully sorted.
How Bubble Sort Works:
1. Compare adjacent elements in the array
2. If they are in the wrong order, swap them
3. Continue through the array until no more swaps are needed
4. After each pass, the largest unsorted element "bubbles up" to its correct position
Time Complexity: O(n²) in worst case, O(n) in best case (already sorted)
Space Complexity: O(1) - sorts in place