search
HomeBackend DevelopmentPHP TutorialPHP interview questions algorithm questions

PHP interview questions algorithm questions

Mar 01, 2018 am 10:39 AM
phpalgorithmtest questions

Algorithm questions often appear in PHP interview questions. This article mainly shares with you the algorithm questions of PHP interview questions, hoping to help everyone.

Related recommendations: "2019 PHP Interview Questions Summary (Collection)"

Interview Questions - Algorithm Questions:

1. Insertion sort (one-dimensional array) Basic idea: Each time a data element to be sorted is inserted into the appropriate position in the previously sorted array, so that the array is still in order; until all the data elements to be sorted are until the insertion is complete. Example:

[Initial keyword] [49] 38 65 97 76 13 27 49
J=2(38) [38 49] 65 97 76 13 27 49
J=3(65 ) [38 49 65] 97 76 13 27 49
J=4(97) [38 49 65 97] 76 13 27 49
J=5(76) [38 49 65 76 97] 13 27 49
J=6(13) [13 38 49 65 76 97] 27 49
J=7(27) [13 27 38 49 65 76 97] 49
J=8(49) [13 27 38 49 49 65 76 97]

function insert_sort($arr){
    $count = count($arr); 	
    for($i=1; $i $tmp){ 	 		
            $arr[$j+1] = $arr[$j]; 	 		
            $arr[$j] = $tmp; 	 		
            $j--; 	 		
        } 	 
    } 	 
    return $arr; 
}

2. Selection sort (one-dimensional array) Basic idea: Each pass selects the smallest (or largest) element from the data elements to be sorted, in order Place it at the end of the sorted array until all data elements to be sorted are exhausted. Example:

[Initial keyword] [49 38 65 97 76 13 27 49]
13 after the first sort [38 65 97 76 49 27 49]
13 after the second sort 27 [65 97 76 49 38 49]
After the third sorting 13 27 38 [97 76 49 65 49]
After the fourth sorting 13 27 38 49 [49 97 65 76]
Fifth After the sixth sorting pass 13 27 38 49 49 [97 97 76]
After the sixth sorting pass 13 27 38 49 49 76 [76 97]
After the seventh sorting pass 13 27 38 49 49 76 76 [ 97]
Final sorting result 13 27 38 49 49 76 76 97

function select_sort($arr){ 	
    $count = count($arr); 	
    for($i=0; $i $arr[$j]) $k = $j; 		
        } 		
        if($k != $i){ 			
            $tmp = $arr[$i]; 			
            $arr[$i] = $arr[$k]; 			
            $arr[$k] = $tmp; 		
        } 	
    } 	
    return $arr; 
}

3. Bubble sorting (one-dimensional array) Basic idea: compare the sizes of the data elements to be sorted pairwise and find two data When the order of elements is reversed, swapping is performed until there are no more data elements in reverse order. Sorting process: Imagine that the sorted array R [1..N] is erected vertically, and each data element is regarded as a weighted bubble. According to the principle that light bubbles cannot be under heavy bubbles, the array R is scanned from bottom to top. Whenever light bubbles that violate this principle are scanned, they are made to "float" upward, and this process is repeated until the last two bubbles are the lighter one at the top and the heavier one at the bottom. Example:

49 13 13 13 13 13 13 13
38 49 27 27 27 27 27 27
65 38 49 38 38 38 38 38
97 65 38 49 49 49 49 49
76 97 65 49 49 49 49 49
13 76 97 65 65 65 65 65
27 27 76 97 76 76 76 76
49 49 49 76 97 97 97 97

function bubble_sort($array){ 	
    $count = count($array); 	
    if ($count $i; $j--){ 			
            if ($array[$j]<hr> <p>4. Quick sort (one-dimensional array) Basic idea: Take any data element in the current unordered area R[1..H] as the "baseline" for comparison (it may be recorded as The current disordered area is divided into two smaller disordered areas on the left and right: R[1..I-1] and R[I 1..H], and the data elements in the left disordered subarea are less than or equal to the reference elements. , the data elements in the unordered sub-area on the right are all greater than or equal to the reference element, and the reference X is located at the final sorting position, that is, R[1..I-1]≤X.Key≤RI 1..H, when R When both [1..I-1] and R[I 1..H] are non-empty, perform the above division process on them respectively until all data elements in the unordered sub-area have been sorted. Example: </p><p>Initial keyword [49 38 65 97 76 13 27 49] <br>After the first exchange [27 38 65 97 76 13 49 49] <br>After the second exchange [27 38 49 97 76 13 65 49] <br>J Scan to the left, the position remains unchanged, after the third exchange [27 38 13 97 76 49 65 49] <br>I Scan to the right, the position remains unchanged, the fourth exchange After [27 38 13 49 76 97 65 49] <br>J scan to the left [27 38 13 49 76 97 65 49] <br> (one division process) <br>Initial keyword [49 38 65 97 76 13 27 49] <br> After one sorting [27 38 13] 49 [76 97 65 49] <br> After two sortings [13] 27 [38] 49 [49 65] 76 [97] <br> After three sortings After that 13 27 38 49 49 [65] 76 97<br>The final sorting result 13 27 38 49 49 65 76 97<br>The status after each sorting</p><pre class="brush:php;toolbar:false">function quickSort(&$arr){    if(count($arr)>1){
        $k=$arr[0];
        $x=array();
        $y=array();
        $_size=count($arr);        for($i=1;$i$k){
                $y[]=$arr[$i];
            }
        }
        $x=quickSort($x);
        $y=quickSort($y);        return array_merge($x,array($k),$y);
    }else{        return$arr;
    }
}

5. Hill sorting (shell sort) — O(n log n)

functionshell_sort(&$arr){    if(!is_array($arr))return;$n=count($arr);    for($gap=floor($n/2);$gap>0;$gap=floor($gap/=2)){        for($i=$gap;$i=0&&$arr[$j+$gap]<hr><p>6. Binary search</p><pre class="brush:php;toolbar:false">/** 
* 二分算法查找 
* @param array $array 要查找的数组 
* @param int $min_key 数组的最小下标 
* @param int $max_key 数组的最大下标 
* @param mixed $value 要查找的值 
* @return boolean 
*/ function bin_search($array,$min_key,$max_key,$value){             if($min_key <hr><p>7. Deletion of linear table (implemented in array)</p><pre class="brush:php;toolbar:false">function delete_array_element($array, $i)	{ 	
    $len = count($array); 	
    for ($j=$i; $j <p>8, String length</p><pre class="brush:php;toolbar:false">function strlen($str)	{ 
    if ($str == '') return 0; 
    $count = 0; 
    while (1){ 
        if ($str[$count] != NULL){ 
            $count++; 
            continue; 
        }else{ 
            break; 
        } 
    } 
    return $count; 
}

9, String flip

function strrev($str)	{ 	
    if ($str == '') return 0; 	
    for ($i=(strlen($str)-1); $i>=0; $i--){ 	 
        $rev_str .= $str[$i]; 	
    } 	
    return $rev_str; 
}

10, String comparison

function strcmp($s1, $s2)	{ 
    if (strlen($s1)  strlen($s2)) return 1; 
    for ($i=0; $i<strlen><hr>
<p>11, Search string</p>
<pre class="brush:php;toolbar:false">function strstr($str, $substr)	{ 
    $m = strlen($str); 
    $n = strlen($substr); 
    if ($m <hr><p>12, String replacement</p><pre class="brush:php;toolbar: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<hr><p>13, Insert a string</p><pre class="brush:php;toolbar:false">function str_insert($str, $i, $substr)	{ 
    for($j=0; $j<p>14, Delete a string</p> <pre class="brush:php;toolbar:false">function str_delete($str, $i, $j){ 	
    for ($c=0; $c<hr><p>15, copy string</p><pre class="brush:php;toolbar:false">function strcpy($s1, $s2){ 
    if (strlen($s1)==NULL || !isset($s2)) return; 
    for ($i=0; $i<strlen><hr>
<p>16, connect string</p>
<pre class="brush:php;toolbar:false">function strcat($s1, $s2){ 
    if (!isset($s1) || !isset($s2)) return; 
    $newstr = $s1; 
    for($i=0; $i<count><hr>
<p>17, simple encoding function (corresponding to php_decode function)</p>
<p>function php_encode($str) { if ($str=='' && strlen($str)>128) return false; for($i=0; $i<strlen ord if>31 && $c106 && $c<p>18. Simple decoding function (corresponding to the php_encode function)</p>
<pre class="brush:php;toolbar:false">function php_decode($str)	{ 
    if ($str=='' && strlen($str)>128) return false; 
    for($i=0; $i<strlen>106 && $c31 && $c<hr>
<p> 19. Simple encryption function (corresponding to the php_decrypt function) </p>
<pre class="brush:php;toolbar:false">function php_encrypt($str)	{ 	
    $encrypt_key = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $decrypt_key = 'ngzqtcobmuhelkpdawxfyivrsj2468021359'; 	
    if (strlen($str) == 0) return false; 	 
    for ($i=0; $i<strlen><hr>
<p>20. Simple decryption function (corresponding to the php_encrypt function) </p>
<pre class="brush:php;toolbar:false">function php_decrypt($str)	{ 
    $encrypt_key = 'abcdefghijklmnopqrstuvwxyz1234567890';
    $decrypt_key = 'ngzqtcobmuhelkpdawxfyivrsj2468021359'; 
    if (strlen($str) == 0) return false; 
    for ($i=0; $i<strlen><p> Related recommendations: </p>
<p><a href="http://www.php.cn/php-weizijiaocheng-381172.html" target="_self">php’s classic algorithm questions Apple</a></p>
<p><a href="http://www.php.cn/linux-369400.html" target="_self">A classic algorithm question caused by a commonly used Linux command in a project</a></p>
<p><a href="http://www.php.cn/js-tutorial-348611.html" target="_self">A brief discussion on some basic algorithm questions on characters and arrays in js</a></p></strlen>

The above is the detailed content of PHP interview questions algorithm questions. 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 to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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 Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools