Explanation of Direct selection and sorting of PHP sorting algorithm series, and explanation of php sorting algorithm series
Select sort directly
The basic idea of Straight Select Sorting is: the first time from R [0] ~ Select the minimum value in R [n-1] and exchange it with R [0]. The second time is from R [1] ~ Select the minimum value in R [n-1] and exchange it with R [1 ,...., I times from R [I-1] ~ Select the minimum value in R [n-1], exchange with R [I-1 ,....., N-1-1 from R [N-2] ~ In R [n-1], the minimum value is selected and exchanged with R [N-2]. In total, an ordered sequence sorted by sort code from small to large is obtained through n-1 times ·
The main advantages of sorting are related to data movement. If an element is in the correct final position, it will not be moved. When sorting is selected, an element is exchanged each time. At least one of them will be moved to its final position. Therefore, a maximum of N-1 exchanges can be performed on tables with n elements. In all sorting methods that rely entirely on swapping to move elements, selecting sorting is a good one.
Principle
First, find the smallest (large) element in the unordered sequence, store it to the starting position of the sorting sequence, and then continue searching for the smallest (large) element from the remaining unordered elements, put it at the end of the sorted sequence. And so on until all elements are sorted.
Example
Set the array to a [0... N-1].
1. At the beginning, the array is all unordered and a [0 .. n-1]. Make I = 0
2. In the unordered Zone a [I... In n-1], select the smallest element and exchange it with a [I. After the switch, a [0... I] formed an ordered zone.
3. I ++ and repeat the second step until I = n-1. Sorting is completed.
Example
Sort arrays [,]
First, take I = 0; a [I] as the minimum value. Compare the following value with a [I]. If it is smaller than a [I], it is switched to a [I, $ I ++
[,]
First, take I = 1; a [I] as the minimum value, and compare the following value with a [I]. If it is smaller than a [I], it exchanges position with a [I, $ I ++
[,]
Repeat the preceding steps
PHP code implementation
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;}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.