Php sorting algorithm (bubble sorting, fast sorting)

Source: Internet
Author: User
Php sorting algorithm code, including bubble sorting and quick sorting. For more information, see

Principle of bubble sorting

① Put all the numbers to be sorted into the work list.
② From the first number in the list to the second to the last number, check one by one: if the number on a certain digit is greater than the next digit, then it is exchanged with its next digit.

③ Repeat step ② until the exchange is no longer allowed.

Code implementation
Copy codeThe code is as follows:
Function bubbingSort (array $ array)
{
For ($ I = 0, $ len = count ($ array)-1; $ I <$ len; ++ $ I)
{
For ($ j = $ len; $ j> $ I; -- $ j)
{
If ($ array [$ j] <$ array [$ j-1])
{
$ Temp = $ array [$ j];
$ Array [$ j] = $ array [$ j-1];
$ Array [$ j-1] = $ temp;
}
}
}
Return $ array;
}

Print'

';
 print_r(bubbingSort(array(1,4,22,5,7,6,9)));
 print '
';

Principles of quick sorting
The idea of sub-governance is adopted: first ensure that the first half of the list is smaller than the second half, and then sort the first half and the second half separately, so that the whole list is ordered.

Code implementation
Copy codeThe code is as follows:
Function quickSort (array $ array)
{
$ Len = count ($ array );
If ($ len <= 1)
{
Return $ array;
}
$ Key = $ array [0];
$ Left = array ();
$ Right = array ();
For ($ I = 1; $ I <$ len; ++ $ I)
{
If ($ array [$ I] <$ key)
{
$ Left [] = $ array [$ I];
}
Else
{
$ Right [] = $ array [$ I];
}
}
$ Left = quickSort ($ left );
$ Right = quickSort ($ right );
Return array_merge ($ left, array ($ key), $ right );
}

Print'

';
 print_r(quickSort(array(1,4,22,5,7,6,9)));
 print '
';

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.