PHP sorting algorithm implementation code

Source: Internet
Author: User
These days are annoying and hard to learn. Randomly looked. Record this. The code is as follows:
// Function: PHP implements various sorting algorithms
// Author: windlike
// Datetime: 2007-06-09

// Bubble sort
Function BubbleSort ($ arr ){
$ Num = count ($ arr );
For ($ I = 1; $ I <$ num; $ I ++ ){
For ($ j = $ num-1; $ j >=$ I; $ j --){
If ($ arr [$ j] <$ arr [$ j-1]) {
$ ITemp = $ arr [$ j-1];
$ Arr [$ j-1] = $ arr [$ j];
$ Arr [$ j] = $ iTemp;
}
}
}
Return $ arr;
}

// Sort by exchange method
Function ExchangeSort ($ arr ){
$ Num = count ($ arr );
For ($ I = 0; $ I <$ num-1; $ I ++ ){
For ($ j = $ I + 1; $ j <$ num; $ j ++ ){
If ($ arr [$ j] <$ arr [$ I]) {
$ ITemp = $ arr [$ I];
$ Arr [$ I] = $ arr [$ j];
$ Arr [$ j] = $ iTemp;
}
}
}
Return $ arr;
}

// Sort by selection
Function SelectSort ($ arr ){
$ Num = count ($ arr );
For ($ I = 0; $ I <$ num-1; $ I ++ ){
$ ITemp = $ arr [$ I];
$ IPos = $ I;
For ($ j = $ I + 1; $ j <$ num; $ j ++ ){
If ($ arr [$ j] <$ iTemp ){
$ ITemp = $ arr [$ j];
$ IPos = $ j;
}
}
$ Arr [$ iPos] = $ arr [$ I];
$ Arr [$ I] = $ iTemp;
}
Return $ arr;
}

// Sort by insert
Function InsertSort ($ arr ){
$ Num = count ($ arr );
For ($ I = 1; $ I <$ num; $ I ++ ){
$ ITemp = $ arr [$ I];
$ IPos = $ I-1;
While ($ iPos> = 0) & ($ iTemp <$ arr [$ iPos]) {
$ Arr [$ iPos + 1] = $ arr [$ iPos];
$ IPos --;
}
$ Arr [$ iPos + 1] = $ iTemp;
}
Return $ arr;
}

// Quick sorting
Function QuickSort ($ arr ){
$ Num = count ($ arr );
$ L = $ r = 0;
For ($ I = 1; $ I <$ num; $ I ++ ){
If ($ arr [$ I] <$ arr [0]) {
$ Left [] = $ arr [$ I];
$ L ++;
} Else {
$ Right [] = $ arr [$ I];
$ R ++;
}
}
If ($ l> 1 ){
$ Left = QuickSort ($ left );
}
$ New_arr = $ left;
$ New_arr [] = $ arr [0];
If ($ r> 1 ){
$ Right = QuickSort ($ right );
}
For ($ I = 0; $ I <$ r; $ I ++ ){
$ New_arr [] = $ right [$ I];
}
Return $ new_arr;
}

$ Arr = array (7,1, 6,5, 2 );
$ Arr_new = QuickSort ($ arr );
Echo"
"; 
print_r($arr_new);
echo "
";
?>

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.