Simple selection sort is a straightforward and commonly used sorting algorithm capable of handling various data sets effectively. The core idea is to repeatedly select the smallest element from the unsorted portion and move it to the end of the sorted portion. Specifically, it selects the minimum element from the entire array and swaps it with the first element in the first pass; then selects the minimum from the remaining elements and swaps with the second element in the second pass, and so forth until the whole array is sorted.
First, get the array length n, then perform n-1 selection rounds. In each round, find the minimum value in the unsorted part and swap it with the element at the starting position of that round, gradually building the sorted sequence.
The following is a PHP implementation of simple selection sort, helping to understand the actual execution of the algorithm:
function selectionSort(&$arr)
{
$len=count($arr);
for($i=0;$i<$len-1;$i++)
{
$min=$i; // Assume current element as minimum
for($j=$i+1;$j<$len;$j++) // Find smaller element in the remaining
{
if($arr[$j]<$arr[$min])
{
$min=$j; // Update minimum index
}
}
if($min!=$i) // Swap if minimum index changed
{
$temp=$arr[$min];
$arr[$min]=$arr[$i];
$arr[$i]=$temp;
}
}
}
Simple selection sort performs n-1 selection passes, each pass scans the remaining unsorted elements to find the minimum, resulting in roughly n²/2 comparisons. The number of moves depends on the initial order of the data. Overall, the time complexity is O(n²). Despite this, the algorithm remains practical for small or nearly sorted datasets.
The algorithm only requires a single temporary variable for swapping, resulting in a space complexity of O(1).
Simple selection sort is not a stable sorting algorithm. Equal elements may change their relative order during the sorting process. For example, in the sequence 5 8 5 2 9, the first pass swaps the smallest element 2 with the first element 5, disrupting the relative order of the two 5s.