This article mainly introduces a simple sorting algorithm example in PHP. This article provides the implementation code and implements it in the form of classes. if you need a friend, you can refer to the following simple sorting algorithm selection: through the comparison between n-I keywords, the records with the minimum keyword are selected from n-I + 1 records and exchanged with records with I (1 <= I <= n ).
The code is as follows:
<? Php
Class Sort {
/**
* Simple selection and sorting
*
* @ Param unknown_type $ arr
*/
Public function selectSort (& $ arr ){
$ Len = count ($ arr );
For ($ I = 0; $ I <$ len; $ I ++ ){
$ Min = $ I;
For ($ j = $ I + 1; $ j <= $ len-1; $ j ++ ){
If ($ arr [$ min]> $ arr [$ j]) {// if a value smaller than $ arr [$ min] is found, the subscript is assigned to $ min.
$ Min = $ j;
}
}
If ($ min! = $ I) {// if $ min is not equal to $ I, the minimum value is found, and
$ This-> swap ($ arr [$ I], $ arr [$ min]);
}
}
}
/**
* Change the positions of $ a and $ B.
*/
Public function swap (& $ a, & $ B ){
$ Temp = $;
$ A = $ B;
$ B = $ temp;
}
}
$ Arr = array (, 8, 5 );
$ Test = new Sort ();
$ Test-> selectSort ($ arr); // simple selection and sorting
// Var_dump ($ arr );
?>
Simple selection and sorting features: the number of mobile data exchanges is quite small, thus saving the corresponding time
Analyze the time complexity of simple selection and sorting:
Regardless of the best and worst case, the number of comparisons is the same. the I-th sorting requires a comparison of the n-I keywords, and n (n-1)/2 times. So the final time complexity is O (n ^ 2)
Although the same as the bubble sorting is O (n ^ 2), the performance of the selected sorting is slightly better than that of the bubble sorting.