Detailed Explanation of Direct Selection Sorting of PHP Sorting Algorithm Series
- 2021-08-28 19:43:09
- OfStack
Direct selection sort
The basic idea of direct selection sorting (Straight Select Sorting) is to select the minimum value from R [0] ~ R [n-1], exchange with R [0], select the minimum value from R [1] ~ R [n-1], exchange with R [1], select the minimum value from R [i-1] ~ R [n-1], exchange with R [i-1], exchange with n-1 from R [n-2] ~ R [n-1] The minimum value was exchanged with R [n-2], and passed n-1 times in total, and an ordered sequence arranged from small to large according to the sorting code was obtained
The main advantages of selective sorting are related to data movement. If an element is in the correct final position, it will not be moved. Select Sort swaps 1 pair of elements at a time, and at least 1 of them will be moved to its final position, so sorting a table of n elements makes a total of up to n-1 swaps. Of all sorts that rely entirely on swapping to move elements, selective sorting is a very good one.
Principle
First, find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence. Then, continue to find the smallest (large) element from the remaining unsorted elements and then put it at the end of the sorted sequence. And so on until all the elements are sorted.
Example
Let the array be a [0... n-1].
1. Initially, the array is all unordered and the region is a [0. n-1]. Let i=0
2. Select the smallest element in the disorder region a [i... n-1] and exchange it with a [i]. After the exchange, a [0... i] forms an ordered region.
3. i + + and repeat step 2 until i==n-1. Sort complete.
Example
Sort Array [53, 89, 12, 98, 25, 37, 92, 5]
First, take i=0; a [i] is the minimum value. Compare the latter value with a [i]. If it is smaller than a [i], exchange positions with a [i], $i + +
[5,89,53,98,25,37,92,12]
First, take i=1; a [i] is the minimum value. Compare the latter value with a [i]. If it is smaller than a [i], exchange positions with a [i], $i + +
[5,12,89,98,53,37,92,25]
Repeat the above steps
Implementation of PHP code
function select_sort($arr){
$length=count($arr);
for ($i=0; $i <$length-1 ; $i++) {
for ($j=$i+1,$min=$i; $j <$length ; $j++) {
if ($arr[$min]>$arr[$j]) {
$min=$j;
}
}
$temp=$arr[$i];
$arr[$i]=$arr[$min];
$arr[$min]=$temp;
}
return $arr;
}