Common php sorting algorithm code [Bubble, recursive sorting-PHP source code

Source: Internet
Author: User
Ec (2); php common sorting algorithm code [Bubble, recursive sort Bubble Sorting Algorithm & nbsp; functionbubblesort ($ arr) {$ ncount ($ arr); for ($ i0; $ I & lt; $ n; $ I ++) {for ($ j $ I; $ j & lt; $ n-1; $ j ++) {if ($ arr [$ I] & gt; $ arr [$ j]) {$ temp $ arr [$ I]; $ arr [$ I] $ a script ec (2); script

Common php sorting algorithm code [Bubble, recursive sorting

Bubble Sorting Algorithm
Function bubblesort ($ arr)
{
$ N = count ($ arr );

For ($ I = 0; $ I <$ n; $ I ++)
{
For ($ j = $ I; $ j <= $ n-1; $ j ++)
{
If ($ arr [$ I]> $ arr [$ j])
{
$ Temp = $ arr [$ I];
$ Arr [$ I] = $ arr [$ j];
$ Arr [$ j] = $ temp;


}
}
}
Return $ arr;

}
// Insert the sorting directly
Function insertsort ($ arr)
{
$ N = count ($ arr );
For ($ I = 1; $ I <$ n; ++ $ I)
{
If ($ arr [$ I] <$ arr [$ I-1])
{
$ Tmp = $ arr [$ I];
$ J = 0;
For ($ j = $ I-1; $ j >=0 & $ tmp <$ arr [$ j]; -- $ j)
{
$ Arr [$ j + 1] = $ arr [$ j];
}
$ Arr [$ j + 1] = $ tmp;
}
}
Return $ arr;

} Simple Sorting Algorithm

Function simplesort ($ arr)
{
$ Tmp = 0;
$ T = 0;
$ N = count ($ arr );
For ($ I = 0; $ I <$ n; ++ $ I)
{
$ T = $ I;
For ($ j = $ I + 1; $ j <$ n; ++ $ j)
{
If ($ arr [$ t]> $ arr [$ j])
{
$ T = $ j;

}
}
$ Tmp = $ arr [$ I];
$ Arr [$ I] = $ arr [$ t];
$ Arr [$ t] = $ tmp;

}

Return $ arr;
} Quick Sorting Algorithm
Function qsort ($ array)
{
$ N = count ($ array );
If ($ n <= 1) {return $ array ;}

$ Key = $ array [0];
$ L = array ();
$ R = array ();
// Perform recursive sorting respectively and then synthesize an array
For ($ I = 1; $ I <$ n; $ I ++)
{
If ($ array [$ I] <= $ key)
{
$ L [] = $ array [$ I];
}
Else
{
$ R [] = $ array [$ I];
}
}
$ L = qsort ($ l );
$ R = qsort ($ r );
Return array_merge ($ l, array ($ key), $ r );

}

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.