-
Hajipur, Bihar, 844101
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.
Compare the first two elements
Swap them if they are in the wrong order
Move to the next pair and repeat
Continue this process until the end of the list
Repeat the process for all elements
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]
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]
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.
Case | Time |
---|---|
Best Case | O(n) |
Average | O(n²) |
Worst Case | O(n²) |
Space | O(1) |
Bubble sort is inefficient for large datasets.
Simple learning purposes
Small or mostly sorted lists
When simplicity matters more than speed
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.
Q1: What does bubble sort do?
Q2: When does bubble sort stop early?
Q3: Time complexity of bubble sort in worst case?
Q4: Space complexity of bubble sort?
Q5: What is swapped during sorting?
Q6: How many passes needed to sort n elements?
Q7: Bubble sort is best for:
Q8: Can Bubble Sort be used to sort strings?
Q9: What is the key operation in bubble sort?
Q10: In Bubble Sort, what happens in the first pass?