PHP Sorting algorithm: Select sort

Source: Internet
Author: User

It's easy to sort the numbers in PHP, and we can convert the strings into groups, for example:

$string = ‘94132768‘;

Pass

$arr = str_split(($string);

To group:
$arr = Array (9,4,1,3,2,7,6,8);

Sorting algorithms

The first kind we can sort by using PHP's built-in functions

Sort ($arr), Ascending, Rsort ($arr) Descending

The second is to sort using the selection sort method, which is about finding the smallest number from the array, then swapping it with the 1th digit, and so on:

9,4,1,3,2,7,6,8

9 and 1 Swap

1,4,9,3,2,7,6,8

Then the minimum number from 4 to 8 is 2, 2 and 4 are swapped

1,4,9,3,4,7,6,8

And so on

$n = count($arr);for($i=0;$i<$n;$i++){    $min = $arr[$i];    //比较[i,n)中的最小数,然后进行位置兑换    for($j=$i+1;$j<$n;$j++){        if($arr[$j] < $min)                {            $temp = $arr[$j];            $arr[$i] = $temp;            $arr[$j] = $arr[$i];            $min = $arr[$j];        }    }}print_r($arr);

You can try it all right. Very simple algorithm.

PHP Sorting algorithm: Select 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.