PHP Program for Selection Sort Algorithm
for loops to find the smallest element and swap it with the current position; for example, for ($i = 0; $i < count($arr) - 1; $i++) { $min = $i; for ($j = $i + 1; $j < count($arr); $j++) { if ($arr[$j] < $arr[$min]) { $min = $j; } } $temp = $arr[$i]; $arr[$i] = $arr[$min]; $arr[$min] = $temp; } sorts the array in ascending order.Examples
How to Think About It
Algorithm
Code
<?php function selectionSort(array &$arr): void { $n = count($arr); for ($i = 0; $i < $n - 1; $i++) { $min = $i; for ($j = $i + 1; $j < $n; $j++) { if ($arr[$j] < $arr[$min]) { $min = $j; } } if ($min !== $i) { $temp = $arr[$i]; $arr[$i] = $arr[$min]; $arr[$min] = $temp; } } } $array = [5, 3, 8, 4, 2]; selectionSort($array); print_r($array);
Dry Run
Let's trace the array [5, 3, 8, 4, 2] through the selection sort code.
Initial array
[5, 3, 8, 4, 2]
Find minimum from index 0 to end
Minimum is 2 at index 4
Swap elements at index 0 and 4
Array becomes [2, 3, 8, 4, 5]
Find minimum from index 1 to end
Minimum is 3 at index 1
Swap elements at index 1 and 1 (no change)
Array remains [2, 3, 8, 4, 5]
Find minimum from index 2 to end
Minimum is 4 at index 3
Swap elements at index 2 and 3
Array becomes [2, 3, 4, 8, 5]
Find minimum from index 3 to end
Minimum is 5 at index 4
Swap elements at index 3 and 4
Array becomes [2, 3, 4, 5, 8]
| Iteration | Array State |
|---|---|
| 0 | [5, 3, 8, 4, 2] |
| 1 | [2, 3, 8, 4, 5] |
| 2 | [2, 3, 8, 4, 5] |
| 3 | [2, 3, 4, 8, 5] |
| 4 | [2, 3, 4, 5, 8] |
Why This Works
Step 1: Finding the minimum
The inner loop uses if ($arr[$j] < $arr[$min]) to find the smallest element in the unsorted part.
Step 2: Swapping elements
After finding the minimum, the code swaps it with the first unsorted element to move it to the sorted part.
Step 3: Shrinking unsorted part
The outer loop moves forward, reducing the unsorted section until the whole array is sorted.
Alternative Approaches
<?php function bubbleSort(array &$arr): void { $n = count($arr); for ($i = 0; $i < $n - 1; $i++) { 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; } } } } $array = [5, 3, 8, 4, 2]; bubbleSort($array); print_r($array);
<?php $array = [5, 3, 8, 4, 2]; sort($array); print_r($array);
Complexity: O(n^2) time, O(1) space
Time Complexity
Selection sort uses two nested loops each running up to n times, resulting in O(n^2) time complexity.
Space Complexity
It sorts the array in place without extra memory, so space complexity is O(1).
Which Approach is Fastest?
Built-in sort() is fastest and optimized; selection sort is educational but slower for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Selection Sort | O(n^2) | O(1) | Learning sorting basics |
| Bubble Sort | O(n^2) | O(1) | Simple implementation, educational |
| Built-in sort() | O(n log n) | O(1) | Fast and practical sorting |