Selection Sort in DSA (PHP) – Complete Guide
📌 What is Selection Sort?
Selection Sort ek simple sorting algorithm hai jisme hum array me se smallest element select karte hain aur usko starting position par rakh dete hain.
👉 Har iteration me ek minimum element choose hota hai aur correct position pe swap hota hai.
⚙️ How Selection Sort Works
Step-by-step:
- Array me se smallest element find karo
- Usko first position se swap karo
- Phir remaining array me se next smallest find karo
- Process repeat karo jab tak array sort na ho jaye
📊 Example (Dry Run)
Array:
[64, 25, 12, 22, 11]Pass 1:
- Minimum = 11
👉 Swap with 64
➡️[11, 25, 12, 22, 64]
Pass 2:
- Minimum = 12
👉 Swap with 25
➡️[11, 12, 25, 22, 64]
Pass 3:
- Minimum = 22
👉 Swap with 25
➡️[11, 12, 22, 25, 64]
Final Sorted Array:
[11, 12, 22, 25, 64]💻 Selection Sort in PHP (Code Example)
<?php
function selectionSort($arr) {
$n = count($arr); for ($i = 0; $i < $n - 1; $i++) {
$minIndex = $i; for ($j = $i + 1; $j < $n; $j++) {
if ($arr[$j] < $arr[$minIndex]) {
$minIndex = $j;
}
} // Swap
$temp = $arr[$minIndex];
$arr[$minIndex] = $arr[$i];
$arr[$i] = $temp;
} return $arr;
}// Example
$array = [64, 25, 12, 22, 11];
$sortedArray = selectionSort($array);
print_r($sortedArray);
?>⚡ Key Insight
👉 Selection Sort me minimum element ko select karna main idea hai, isliye naam “Selection Sort”.
⏱️ Time & Space Complexity
| Case | Time Complexity |
|---|---|
| Best Case | O(n²) |
| Average | O(n²) |
| Worst Case | O(n²) |
Space Complexity:
👉 O(1) (in-place)
👍 Advantages
- Simple aur easy samajhne wala
- Minimum number of swaps
- Memory efficient
👎 Disadvantages
- Slow for large data
- Always O(n²), even if sorted
- Not stable sorting algorithm
🎯 When to Use Selection Sort?
- Small datasets
- Jab swaps minimize karne ho
- Learning DSA basics
🚀 Selection Sort vs Bubble Sort
| Feature | Selection Sort | Bubble Sort |
|---|---|---|
| Swaps | Less | More |
| Time Complexity | O(n²) | O(n²) |
| Stability | Not Stable | Stable |
| Use Case | Small data | Learning |
No comments yet! You be the first to comment.
