PHP Simple Choice Sorting algorithm instance _php skill

Source: Internet
Author: User

Simple Choice sorting algorithm: Through the comparison between the N-i, select the smallest key word record from the n-i+1 record and exchange with the first (1<=i<=n) record.

Copy Code code as follows:

<?php
Class sort{
/**
* Simple choice of 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 is found that is smaller than the $arr[$min], the subscript is assigned to $min
$min = $j;
}
}
if ($min!= $i) {//If $min is not equal to $i, the minimum value is found, the Exchange
$this->swap ($arr [$i], $arr [$min]);
}
}
}
/**
* Position exchange of $a and $b two values
*/
Public function Swap (& $a,& $b) {
$temp = $a;
$a = $b;
$b = $temp;
}
}
$arr =array (4,6,1,2,9,8,7,3,5);
$test =new Sort ();
$test->selectsort ($arr);//Simple selection sort
Var_dump ($arr);
?>

Simple choice of sorting characteristics: The exchange of mobile data is relatively small, thereby saving the corresponding time
Time complexity analysis for simple selection sorting:
Regardless of the best worst-case scenario, the number of comparisons is the same, the I-trip sort needs to be compared with the N-i keyword, at which point N (n-1)/2 times are required. So the ultimate time complexity is O (n^2)
Although the same as the Bubble sort O (n^2), the performance of the select sort is slightly better than the bubble sort.

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.