Bubble Sort Algo Flashcards
1
Q
Core Idea?
A
- Repeatedly compare adjacent elements of the array.
- Swap them if they are in wrong order (Left el > Right el)
- The process is repeated for the entire array multiple times.
- Until no swaps are needed.
2
Q
The “Bubble Effect”?
A
- In each pass, the largest unsorted element “bubbles up” to it’s correct position in the array.
- Like the bubble rising to the top of the water.
3
Q
Visual example…
A
Initial Array: [5, 3, 8, 4, 2]
Pass 1:
Compare 5 and 3: Swap → [3, 5, 8, 4, 2]
Compare 5 and 8: No Swap → [3, 5, 8, 4, 2]
Compare 8 and 4: Swap → [3, 5, 4, 8, 2]
Compare 8 and 2: Swap → [3, 5, 4, 2, 8]
Largest element (8) “bubbled up” to its correct position.
Pass 2:
Repeat the process for the remaining elements ([3, 5, 4, 2]), and the next largest element (5) bubbles up.
Final Sorted Array: [2, 3, 4, 5, 8]
4
Q
Code…
A
def bubble_sort(arr): n = len(arr) for i in range(n): # Outer loop for each pass # Flag to check if any swaps happen in this pass swapped = False for j in range(n - i - 1): # Inner loop for pairwise comparisons if arr[j] > arr[j + 1]: # Compare adjacent elements arr[j], arr[j + 1] = arr[j + 1], arr[j] # Swap if out of order swapped = True # If no swaps happened in a pass, the array is already sorted if not swapped: break Example usage array = [64, 34, 25, 12, 22, 11, 90] print("Original Array:", array) bubble_sort(array) print("Sorted Array:", array)