# Use php to implement the selection sort solution

• 2020-06-01 08:59:35
• OfStack

1. Definition: selection sort (Selection sort) is a simple and intuitive sorting algorithm. Here's how it works. Find the smallest (large) element in the unsorted sequence, store it at the beginning of the sorted sequence, and then continue to search for the smallest (large) element from the remaining unsorted elements, and put it at the end of the sorted sequence. And so on, until all the elements are sorted.

Reference code:

``````
<?php
// Selection sort (Selection sort) is 1 A simple and intuitive sorting algorithm. Here's how it works. Find the smallest (large) element in the unsorted sequence, store it at the beginning of the sorted sequence, and then continue to search for the smallest (large) element from the remaining unsorted elements, and put it at the end of the sorted sequence. And so on, until all the elements are sorted.

function selectSort(&\$arr){
// Define the variables to swap
\$temp=0;
for(\$i=0;\$i<count(\$arr)-1;\$i++){
// Assuming that \$i That's the minimum
\$valmin=\$arr[\$i];
// Record the subscript of the minimum value
\$minkey=\$i;
for(\$j=\$i+1;\$j<count(\$arr);\$j++){
// The minimum value is greater than the next number
if(\$valmin>\$arr[\$j]){
\$valmin=\$arr[\$j];
\$minkey=\$j;
}
}
// swapping
\$temp=\$arr[\$i];
\$arr[\$i]=\$arr[\$minkey];
\$arr[\$minkey]=\$temp;
}
}

\$arr=array(7,5,0,4,-1);
selectSort(\$arr);
print_r(\$arr);
?>
``````

Related articles: