Bubble Sort in PHP (DSA) – Complete Guide with Examples & Time Complexity
📌 What is Bubble Sort?
Bubble Sort ek simple sorting algorithm hai jo array ke elements ko repeatedly compare karta hai aur swap karta hai jab tak list sorted na ho jaye.
👉 Ye “Bubble” isliye kehlata hai kyunki largest element har pass me upar (end) tak bubble ho jata hai.
⚙️ How Bubble Sort Works
Step-by-step samjho:
- Adjacent elements compare karo
- Agar left > right → swap karo
- Ek full pass ke baad largest element last me fix ho jata hai
- Process repeat karo jab tak sorted na ho jaye
📊 Example (Dry Run)
Array:
[5, 3, 8, 4, 2]Pass 1:
- (5,3) → swap → [3,5,8,4,2]
- (5,8) → no swap
- (8,4) → swap → [3,5,4,8,2]
- (8,2) → swap → [3,5,4,2,8]
👉 Largest element 8 end me chala gaya
Pass 2:
- (3,5) → no swap
- (5,4) → swap → [3,4,5,2,8]
- (5,2) → swap → [3,4,2,5,8]
Final Sorted Array:
[2, 3, 4, 5, 8]💻 Bubble Sort in PHP (Code Example)
<?php
function bubbleSort($arr) {
$n = count($arr); for ($i = 0; $i < $n - 1; $i++) {
for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
// Swap
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp;
}
}
} return $arr;
}// Example
$array = [5, 3, 8, 4, 2];
$sortedArray = bubbleSort($array);
print_r($sortedArray);
?>⚡ Optimized Bubble Sort (Best Version)
👉 Agar array already sorted ho, to unnecessary loops avoid kar sakte hain.
<?php
function bubbleSortOptimized($arr) {
$n = count($arr); for ($i = 0; $i < $n - 1; $i++) {
$swapped = false; for ($j = 0; $j < $n - $i - 1; $j++) {
if ($arr[$j] > $arr[$j + 1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j + 1];
$arr[$j + 1] = $temp; $swapped = true;
}
} if (!$swapped) {
break;
}
} return $arr;
}
?>⏱️ Time & Space Complexity
| Case | Time Complexity |
|---|---|
| Best Case | O(n) |
| Average | O(n²) |
| Worst Case | O(n²) |
Space Complexity:
👉 O(1) (in-place sorting)
👍 Advantages
- Simple & easy to understand
- Beginner-friendly
- No extra memory needed
👎 Disadvantages
- Slow for large datasets
- Not efficient compared to Merge Sort / Quick Sort
- O(n²) time complexity
🎯 When to Use Bubble Sort?
- Jab data chhota ho
- Learning purpose (DSA basics)
- Already nearly sorted array
🚀 Conclusion
Bubble Sort ek basic aur beginner-friendly sorting algorithm hai jo DSA samajhne ke liye perfect hai. Real-world applications me kam use hota hai, lekin concept clear karne ke liye best hai.
No comments yet! You be the first to comment.
