Selection Sort in DSA (PHP) – Complete Guide

Selection Sort

📌 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:

  1. Array me se smallest element find karo
  2. Usko first position se swap karo
  3. Phir remaining array me se next smallest find karo
  4. 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

CaseTime Complexity
Best CaseO(n²)
AverageO(n²)
Worst CaseO(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

FeatureSelection SortBubble Sort
SwapsLessMore
Time ComplexityO(n²)O(n²)
StabilityNot StableStable
Use CaseSmall dataLearning

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *