Selection sort finds the smallest value in the unsorted suffix and places it at the next open position. After each pass, one more value is in its final position. This implementation compares each pair of positions once, for n(n − 1)/2 comparisons, even when the input is already sorted.
Simple example
Select 1 for the first position and then 2 for the second. Print the sorted sequence.
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Advertisements
Walk through the example
Start with [15, 3, 12, 6, -9, 9, 0].
Start at index 0. Scan the remaining values and remember the position of the smallest value, −9.
Exchange −9 with the first value, 15. The first position is now final.
Repeat from the next position. When only one value remains, the entire array is sorted.
Selection Sort Implementation in PHP with explanation
PHP source code
<?php
class SelectionSortExample {
public function selectionSort(&$arr) {
// Get the length of an array
$length = sizeof($arr);
// Loop all the element in an array except the last element
for($i = 0; $i < $length - 1; $i++) {
$minIndex = $i;
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for($j = $i + 1; $j < $length; $j++) {
if($arr[$minIndex] > $arr[$j]) {
$minIndex = $j;
}
}
// Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
$temp = $arr[$minIndex];
$arr[$minIndex] = $arr[$i];
$arr[$i] = $temp;
}
}
public function printArray(&$arr) {
// Loop the item and print each item in the console with white space seperated
for($i = 0; $i < sizeof($arr); $i++) {
echo($arr[$i] . " ");
}
echo("\n");
}
}
$obj = new SelectionSortExample();
$arr = array();
array_push($arr, 15, 3, 12, 6, -9, 9, 0);
echo("Before Sorting: ");
$obj->printArray($arr);
$obj->selectionSort($arr, 0, sizeof($arr) - 1);
echo("After Sorting: ");
$obj->printArray($arr);
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15