Php implementation of quick sorting Function Code

Source: Internet
Author: User

Code 1: Copy codeThe Code is as follows: <? Php
Function quicksort ($ str ){
If (count ($ str) <= 1) return $ str; // if the number is not big, return directly
$ Key = $ str [0]; // obtain a value for comparison later;
$ Left_arr = array ();
$ Right_arr = array ();
For ($ I = 1; $ I <count ($ str); $ I ++) {// place a value greater than $ key on the right and a small value on the left;
If ($ str [$ I] <= $ key)
$ Left_arr [] = $ str [$ I];
Else
$ Right_arr [] = $ str [$ I];
}
$ Left_arr = quicksort ($ left_arr); // recursion;
$ Right_arr = quicksort ($ right_arr );
Return array_merge ($ left_arr, array ($ key), $ right_arr); // combines the left and right values into an array;
} // The following is the test
$ Str = array (, 0 );
Print_r (quicksort ($ str ));
?>

Code 2:Copy codeThe Code is as follows:/* @ quick sorting */
Function quickSort ($ left, $ right, $ arr ){
$ L = $ left;
$ R = $ right;
$ Align = $ arr [($ left + $ right)/2];
$ Temp = 0;

While ($ l <$ r ){
While ($ arr [$ l] <$ Scheme ){
$ L ++;
}
While ($ arr [$ r]> $ region ){
$ R --;
}

If ($ l >=$ r) break;

$ Temp = $ arr [$ l];
$ Arr [$ l] = $ arr [$ r];
$ Arr [$ r] = $ temp;

If ($ arr [$ l] === pivot) -- $ r;
If ($ arr [$ r] === pivot) ++ $ l;
}

If ($ l = $ r ){
$ L ++;
$ R --;
}

If ($ left <$ r ){
QuickSort ($ left, $ r, $ arr );
} Elseif ($ right> $ l ){
QuickSort ($ l, $ right, $ arr );
} Else {
Return $ arr;
}
}

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.