PHP simple sorting algorithm instance selection

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.