Bubble Sort Algorithm and How does it work?

def bubble_sort(arr):  
    n = len(arr)  
    for i in range(n):  
        # Track whether any swaps were made in this pass  
        swapped = False  
        for j in range(0, n - i - 1):  
            # Compare adjacent elements  
            if arr[j] > arr[j + 1]:  
                # Swap if elements are in the wrong order  
                arr[j], arr[j + 1] = arr[j + 1], arr[j]  
                # Mark that a swap has been made  
                swapped = True  
        # If no swaps were made, the list is already sorted  
        if not swapped:  
            break  
    return arr  
  
# Example usage  
numbers = [64, 34, 25, 12, 22, 11, 90]  
sorted_numbers = bubble_sort(numbers)  
print("Sorted array:", sorted_numbers)  

Complexity and Performance Metrics

Leave a Reply

Your email address will not be published. Required fields are marked *

×