search
HomeBackend DevelopmentPHP TutorialPHP classic algorithm example analysis

PHP classic algorithm example analysis

Mar 20, 2018 pm 04:29 PM
phpCase Analysisalgorithm

This article mainly shares with you the analysis of PHP classic algorithm examples, hoping to help everyone.

?  
//--------------------  
// 基本数据结构算法 
//--------------------  
//二分查找(数组里查找某个元素)  
function bin_sch($array,  $low, $high, $k){   
    if ( $low <= $high){   
        $mid =  intval(($low+$high)/2 );   
        if ($array[$mid] ==  $k){   
            return $mid;   
        }elseif ( $k < $array[$mid]){   
            return  bin_sch($array, $low,  $mid-1, $k);   
        }else{   
            return  bin_sch($array, $mid+ 1, $high, $k);   
        }   
    }   
    return -1;   
}   
//顺序查找(数组里查找某个元素)  
function  seq_sch($array, $n,  $k){   
    $array[$n] =  $k;   
    for($i=0;  $i<$n; $i++){   
        if( $array[$i]==$k){   
            break;   
        }   
    }   
    if ($i<$n){   
        return  $i;   
    }else{   
        return -1;   
    }   
}   
//线性表的删除(数组中实现)  
function delete_array_element($array , $i)  
{  
        $len =  count($array);   
        for ($j= $i; $j<$len; $j ++){  
                $array[$j] = $array [$j+1];  
        }  
        array_pop ($array);  
        return $array ;  
}  
//冒泡排序(数组排序)  
function bubble_sort( $array)  
{  
        $count = count( $array);  
        if ($count <= 0 ) return false;  
        for($i=0 ; $i<$count; $i ++){  
                for($j=$count-1 ; $j>$i; $j--){  
                        if ($array[$j] < $array [$j-1]){  
                                 $tmp = $array[$j];  
                                 $array[$j] = $array[ $j-1];  
                                $array [$j-1] = $tmp;  
                        }  
                }  
        }  
        return $array;  
}  
//快速排序(数组排序)  
function quick_sort($array ) {  
        if (count($array) <= 1) return  $array;  
        $key = $array [0];  
        $left_arr  = array();  
        $right_arr = array();  
        for ($i= 1; $i<count($array ); $i++){  
                if ($array[ $i] <= $key)  
                        $left_arr [] = $array[$i];  
                else  
                         $right_arr[] = $array[$i ];  
        }  
        $left_arr = quick_sort($left_arr );  
        $right_arr = quick_sort( $right_arr);  
        return array_merge($left_arr , array($key), $right_arr);  
}  

//------------------------  
// PHP内置字符串函数实现  
//------------------------  
//字符串长度  
function strlen ($str)  
{  
        if ($str == &#39;&#39; ) return 0;  
        $count =  0;  
        while (1){  
                if ( $str[$count] != NULL){  
                         $count++;  
                        continue;  
                }else{  
                        break;  
                }  
        }  
        return $count;  
}  
//截取子串  
function substr($str, $start,  $length=NULL)  
{  
        if ($str== &#39;&#39; || $start>strlen($str )) return;  
        if (($length!=NULL) && ( $start>0) && ($length> strlen($str)-$start)) return;  
        if (( $length!=NULL) && ($start< 0) && ($length>strlen($str )+$start)) return;  
        if ($length ==  NULL) $length = (strlen($str ) - $start);  
          
        if ($start <  0){  
                for ($i=(strlen( $str)+$start); $i<(strlen ($str)+$start+$length ); $i++) {  
                        $substr .=  $str[$i];  
                }  
        }  
        if ($length  > 0){  
                for ($i= $start; $i<($start+$length ); $i++) {  
                        $substr  .= $str[$i];  
                }  
        }  
        if ( $length < 0){  
                for ($i =$start; $i<(strlen( $str)+$length); $i++) {  
                        $substr .= $str[$i ];  
                }  
        }  
        return $substr;  
}  
//字符串翻转  
function strrev($str)  
{  
        if ($str == &#39;&#39;) return 0 ;  
        for ($i=(strlen($str)- 1); $i>=0; $i --){  
                $rev_str .= $str[$i ];  
        }  
        return $rev_str;  
}  

//字符串比较  
function strcmp($s1,  $s2)  
{  
        if (strlen($s1) <  strlen($s2)) return -1 ;  
        if (strlen($s1) > strlen( $s2)) return 1;  
        for ($i =0; $i<strlen($s1 ); $i++){  
                if ($s1[ $i] == $s2[$i]){  
                        continue;  
                }else{  
                        return false;  
                }  
        }  
        return  0;  
}  

//查找字符串  
function  strstr($str, $substr)  
{  
         $m = strlen($str);  
        $n = strlen($substr );  
        if ($m < $n) return false ;  
        for ($i=0; $i <=($m-$n+1); $i ++){  
                $sub = substr( $str, $i, $n);  
                if ( strcmp($sub, $substr) ==  0)  return $i;  
        }  
        return false ;  
}  
//字符串替换  
function str_replace($substr , $newsubstr, $str)  
{  
         $m = strlen($str);  
        $n = strlen($substr );  
        $x = strlen($newsubstr );  
        if (strchr($str, $substr ) == false) return false;  
        for ( $i=0; $i<=($m- $n+1); $i++){  
                 $i = strchr($str,  $substr);  
                $str = str_delete ($str, $i, $n);  
                $str = str_insert($str,  $i, $newstr);  
        }  
        return $str ;  
}  

//--------------------  
// 自实现字符串处理函数 
//--------------------  
//插入一段字符串  
function str_insert($str, $i , $substr)  
{  
        for($j=0 ; $j<$i; $j ++){  
                $startstr .= $str[$j ];  
        }  
        for ($j=$i; $j <strlen($str); $j ++){  
                $laststr .= $str[$j ];  
        }  
        $str = ($startstr . $substr  . $laststr);  
        return $str ;  
}  
//删除一段字符串  
function str_delete($str , $i, $j)  
{  
        for ( $c=0; $c<$i;  $c++){  
                $startstr .= $str [$c];  
        }  
        for ($c=( $i+$j); $c<strlen ($str); $c++){  
                $laststr  .= $str[$c];  
        }  
         $str = ($startstr . $laststr );  
        return $str;  
}  
//复制字符串  
function strcpy($s1, $s2 )  
{  
        if (strlen($s1)==NULL || !isset( $s2)) return;  
        for ($i=0 ; $i<strlen($s1);  $i++){  
                $s2[] = $s1 [$i];  
        }  
        return $s2;  
}  
//连接字符串  
function strcat($s1 , $s2)  
{  
        if (!isset($s1) || !isset( $s2)) return;  
        $newstr = $s1 ;  
        for($i=0; $i <count($s); $i ++){  
                $newstr .= $st[$i ];  
        }  
        return $newsstr;  
}  
//简单编码函数(与php_decode函数对应)  
function php_encode($str)  
{  
        if ( $str==&#39;&#39; && strlen( $str)>128) return false;  
        for( $i=0; $i<strlen ($str); $i++){  
                 $c = ord($str[$i ]);  
                if ($c>31 && $c <107) $c += 20 ;  
                if ($c>106 && $c <127) $c -= 75 ;  
                $word = chr($c );  
                $s .= $word;  
        }   
        return $s;   
}  
//简单解码函数(与php_encode函数对应)  
function php_decode($str)  
{  
        if ( $str==&#39;&#39; && strlen($str )>128) return false;  
        for( $i=0; $i<strlen ($str); $i++){  
                $c  = ord($word);  
                if ( $c>106 && $c<127 ) $c = $c-20;  
                if ($c>31 && $c< 107) $c = $c+75 ;  
                $word = chr( $c);  
                $s .= $word ;  
        }   
        return $s;   
}  
//简单加密函数(与php_decrypt函数对应)  
function php_encrypt($str)  
{  
         $encrypt_key = &#39;abcdefghijklmnopqrstuvwxyz1234567890&#39;;  
         $decrypt_key = &#39;ngzqtcobmuhelkpdawxfyivrsj2468021359&#39;;  
        if ( strlen($str) == 0) return  false;  
        for ($i=0;  $i<strlen($str); $i ++){  
                for ($j=0; $j <strlen($encrypt_key); $j ++){  
                        if ($str[$i] == $encrypt_key [$j]){  
                                $enstr .=  $decrypt_key[$j];  
                                break;  
                        }  
                }  
        }  
        return $enstr;  
}  
//简单解密函数(与php_encrypt函数对应)  
function php_decrypt($str)  
{  
         $encrypt_key = &#39;abcdefghijklmnopqrstuvwxyz1234567890&#39;;  
         $decrypt_key = &#39;ngzqtcobmuhelkpdawxfyivrsj2468021359&#39;;  
        if ( strlen($str) == 0) return  false;  
        for ($i=0;  $i<strlen($str); $i ++){  
                for ($j=0; $j <strlen($decrypt_key); $j ++){  
                        if ($str[$i] == $decrypt_key [$j]){  
                                $enstr .=  $encrypt_key[$j];  
                                break;  
                        }  
                }  
        }  
        return $enstr;  
}  
?>

Related recommendations:

php classic algorithm example sharing

php’s classic algorithm problem Dividing Apples

PHP Classic Algorithm

The above is the detailed content of PHP classic algorithm example analysis. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP identify a user's session?How does PHP identify a user's session?May 01, 2025 am 12:23 AM

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

What are some best practices for securing PHP sessions?What are some best practices for securing PHP sessions?May 01, 2025 am 12:22 AM

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

Where are PHP session files stored by default?Where are PHP session files stored by default?May 01, 2025 am 12:15 AM

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

How do you retrieve data from a PHP session?How do you retrieve data from a PHP session?May 01, 2025 am 12:11 AM

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

How can you use sessions to implement a shopping cart?How can you use sessions to implement a shopping cart?May 01, 2025 am 12:10 AM

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

How do you create and use an interface in PHP?How do you create and use an interface in PHP?Apr 30, 2025 pm 03:40 PM

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

What is the difference between crypt() and password_hash()?What is the difference between crypt() and password_hash()?Apr 30, 2025 pm 03:39 PM

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

How can you prevent Cross-Site Scripting (XSS) in PHP?How can you prevent Cross-Site Scripting (XSS) in PHP?Apr 30, 2025 pm 03:38 PM

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment