This article is mainly for everyone in detail the PHP simple selection of sorting (easy Selection sort) algorithm, with a certain reference value, interested in small partners can refer to, hope to help everyone.
The example of this article for you to share the simple selection of PHP code for reference, for everyone to refer to the specific content as follows
Basic idea:
Through the comparison between the N-i keyword, the smallest record of the keyword is selected from the N-i + 1 records and exchanged with the first (1 <= i <= N) records, and the sequence of records is completed after the n-1 trip.
Algorithm implementation:
<?php//Simple selection sort//Swap functions function Swap (array & $arr, $a, $b) { $temp = $arr [$a]; $arr [$a] = $arr [$b]; $arr [$b] = $temp;} Simple selection sorting algorithm function Selectsort (array & $arr) { $count = count ($arr); for ($i = 0; $i < $count-1; $i + +) { //record all elements after $i element minimum subscript $min = $i; for ($j = $i + 1; $j < $count; $j + +) { if ($arr [$j] < $arr [$min]) { $min = $j; } } if ($min! = $i) { swap ($arr, $min, $i);}}} $arr = Array (9,1,5,8,3,7,4,6,2); Selectsort ($arr); Var_dump ($arr);
Analysis of Complexity:
You need to move records less often during simple selection sorting. In the best case, the initial state of the records to be sorted is already in a positive order, so you do not need to move the records.
In the worst case, the initial state of the records to be sorted is the largest of the first records, and then the records are ordered from small to large, and the maximum number of times to move Records is 3 (n-1). Simple selection The number of comparisons that need to be made in the sort process is independent of the arrangement of the sequence of records to be sorted in the initial state. When I=1, a n-1 comparison is required, and when i=2, a n-2 comparison is required, and so on, the total number of comparisons required is (n-1) + (n-2) +...+2+1=n (n-1)/2, that is, the time complexity for the comparison operation is O (n^2), and the time complexity for the move operation is O (n).
Simple selection sorting is an unstable sort.