Bubble Sort
📚 What is Bubble Sort?
Bubble Sort is a simple sorting algorithm that:
-
Repeatedly compares adjacent elements
-
Swaps them if they are in the wrong order.
-
After each pass, the largest element is placed to its correct position.
It’s called bubble sort because small elements "bubble" to the top of the list (start) with repeated swaps.
How Bubble Sort Works?
Imagine sorting [5, 1, 4, 2, 8]:
-
Compare 5 and 1 → Swap → [1, 5, 4, 2, 8]
-
Compare 5 and 4 → Swap → [1, 4, 5, 2, 8]
-
Compare 5 and 2 → Swap → [1, 4, 2, 5, 8]
-
Compare 5 and 8 → No swap.
✅ 8 is now in its correct position.
Repeat for the rest until sorted.
Bubble Sort Algorithm
Algorithm: Bubble Sort
-
Start from the first element (index 0).
-
Compare the current element with the next element.
-
If the current element is greater than the next element, swap them.
-
Move to the next element and repeat steps 2–3 for the whole list.
-
After each full pass, the last unsorted element is correctly placed.
-
Repeat the entire process for the remaining unsorted part of the list.
-
Stop when no more swaps are needed.
✍️ Pseudocode
BubbleSort(A[], n)
📋 Properties of Bubble Sort
Property | Value |
---|---|
Best Time Complexity | O(n) (when already sorted) |
Average/Worst Time Complexity | O(n²) |
Space Complexity | O(1) (in-place) |
Stability | Yes (it preserves order of equal elements) |
Type | In-place, Stable |
C Program Bubble Sort
The basic Bubble Sort always completes all passes even if the array is already sorted early.
✅ Optimized Bubble Sort checks if any swapping happened during a pass:
-
If no swap occurs in a full pass, the array is already sorted.
-
Then we can stop early and save time!
Modified Algorithm (Optimized Bubble Sort)
Optimized Bubble Sort Algorithm:
-
Start from the first element.
-
Initialize a flag
swapped
tofalse
. -
Compare adjacent elements:
-
If the current element is greater than the next, swap them and set
swapped = true
.
-
-
After each inner loop pass:
-
If
swapped == false
, break (array is sorted).
-
-
Otherwise, repeat for the unsorted part.
✍️ Optimized Pseudocode
OptimizedBubbleSort(A[], n)1. for i = 0 to n-1
C Program - Optimized Bubble Sort
📋 Properties of Bubble Sort
Property | Value |
---|---|
Best Time Complexity | O(n) (when already sorted) |
Average/Worst Time Complexity | O(n²) |
Space Complexity | O(1) (in-place) |
Stability | Yes (it preserves order of equal elements) |
Type | In-place, Stable |
Comments
Post a Comment