Python Bubble Sort


Bubble Sort is a simple sorting algorithm that repeatedly compares and swaps adjacent elements if they are in the wrong order.

It's easy to understand but not efficient for large data.


🔹 How Bubble Sort Works

  1. Compare the first two elements

  2. Swap them if they are in the wrong order

  3. Move to the next pair and repeat

  4. Continue this process until the end of the list

  5. Repeat the process for all elements


🔹 Bubble Sort in Python

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

Example

nums = [64, 34, 25, 12, 22, 11, 90]

bubble_sort(nums)
print("Sorted array:", nums)

✅ Output:

Sorted array: [11, 12, 22, 25, 34, 64, 90]

🔹 Optimized Bubble Sort (Early Stop)

def bubble_sort_optimized(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]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                swapped = True
        if not swapped:
            break

This version stops if the array is already sorted — improves efficiency.


🔹 Time Complexity

Case Time
Best Case O(n)
Average O(n²)
Worst Case O(n²)
Space O(1)

Bubble sort is inefficient for large datasets.


🔹 Use Cases of Bubble Sort

  • Simple learning purposes

  • Small or mostly sorted lists

  • When simplicity matters more than speed


Practice Questions

Q1. Write a Python program to sort the list [5, 3, 8, 4, 2] using bubble sort.

Q2. Write a Python program to sort a list in descending order using bubble sort.

Q3. Write a Python program to count and display how many swaps were made during the bubble sort process.

Q4. Write a Python program to accept a list of numbers from the user and sort it using bubble sort.

Q5. Write a Python program to add a check in bubble sort to exit early if the list is already sorted.

Q6. Write a Python program to sort a list of strings alphabetically using bubble sort.

Q7. Write a Python program to print the list after each pass in the bubble sort algorithm.

Q8. Write a Python program to find and print the total number of passes (iterations) made by bubble sort.

Q9. Write a Python program to modify bubble sort to stop after k passes (take k as user input).

Q10. Write a Python program to measure and display the time taken to bubble sort a list of 1000 random numbers.


Go Back Top