This article mainly introduces the simple selection of Sorting Algorithm examples in PHP. This article provides the implementation code directly and implements it in the form of classes. For more information, see
This article mainly introduces the simple selection of Sorting Algorithm examples in PHP. This article provides the implementation code directly and implements it in the form of classes. For more information, see
Simple selection Sorting Algorithm: by comparing the n-I key words, the records with the minimum keyword are selected from n-I + 1 records, and exchanged with the I (1 <= I <= n) records
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 sorting is slightly better than that of Bubble sorting.