PHP string reverse sorting implementation method summary [strrev function, binary method, loop method, recursion method], reverse strrev
This example summarizes the PHP string reverse sorting implementation method. We will share this with you for your reference. The details are as follows:
For the reverse sorting of strings, the simplest test code for using the PHP function strrev () is as follows:
Header ('content-type: text/html; charset = UTF-8 '); $ str = implode ('', range (9, 0 )); print '<p> <strong> Before reversed: </strong> '. $ str. '</p>'; print '<p> <strong> After reversed: </strong> '. strrev ($ str ). '</p>';/* output: Before reversed: 9876543210 After reversed: 0123456789 */
How can I implement strrev () without the built-in PHP function? There are also three methods (bipartite, cyclic, and recursive), but no performance tests are conducted.
(PS: The online php code formatting tool on this site is used to help you read the code.Http://tools.jb51.net/code/jb51_php_formatFormatted .)
1. binary classification
/*** Use the binary method to sort strings in reverse order * @ param string $ str source string * @ return string returns the reverse string */function reverse ($ str = '') {$ len = strlen ($ str); // you cannot use count or sizeof $ mid = floor ($ len/2); for ($ I = 0; $ I <$ mid; $ I ++) {$ temp = $ str [$ I]; $ str [$ I] = $ str [$ len-$ I-1]; $ str [$ len-$ I-1] = $ temp;} return $ str ;}
2. Circulation Method
/*** Use a loop to sort strings in reverse order (efficiency is lower than that of the binary method) * @ param string $ str source string * @ return string returns the reverse string */function reverse ($ str = '') {$ result = ''; for ($ I = 1; $ I <= strlen ($ str); $ I ++) {$ result. = substr ($ str,-$ I, 1);} return $ result ;}
3. Recursion
/*** Recursively arrange strings in reverse order (low efficiency) * @ param string $ str source string * @ return string returns the reverse string */function reverse ($ str = '') {static $ result = ''; /* use stacks to understand recursive calls */if (strlen ($ str)> 0) {reverse (substr ($ str, 1); $ result. = substr ($ str, 0, 1); // This sentence must be placed after the previous statement} return $ result ;}