Bubble Sort

About

Bubble Sort works by repeatedly stepping through the array, comparing adjacent elements, and swapping them if they are in the wrong order. With each full pass through the data, the largest unsorted element "bubbles up" to its correct position at the end of the array, like bubbles rising to the surface of water.

![[BinarySort.mp4]]

Complexities

Code Implementation

def bubble_sort(arr):
    n = len(arr)
    
    for i in range(n):
        swapped = False
        
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                # Swap if the current element is greater than the next
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
                
        if not swapped:
            break
            
    return arr

Key Takeaways

Powered by Forestry.md