Bubble Sort Algorithm

A simple sorting algorithm with O(n²) complexity.

Bubble Sort is a straightforward sorting algorithm that repeatedly compares adjacent elements and swaps them if they are in the wrong order. Although its time complexity is \( O(n^2) \), it is easy to implement and serves as an excellent way to learn sorting algorithms.

How It Works:

  1. Start at the beginning of the array.
  2. Compare adjacent elements and swap if needed.
  3. Repeat the process for each element.
  4. Stop when no swaps are needed, indicating the array is sorted.

def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        swapped = False
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break
    return arr

# Example Usage
unsorted_list = [64, 34, 25, 12, 22, 11, 90]
print("Unsorted List:", unsorted_list)
sorted_list = bubble_sort(unsorted_list)
print("Sorted List:", sorted_list)

            
Example Output:
Unsorted List: [64, 34, 25, 12, 22, 11, 90]
Sorted List: [11, 12, 22, 25, 34, 64, 90]
            
Sharih Hassan

Sharih Hassan

Founder of SharihHassan.com

Email: Contact@sharihhassan.com