


The content this article brings to you is about the commonly used bubble sorting & quick sorting algorithm and binary search & sequential search algorithm implementation in PHP. It has certain reference value. Friends in need can refer to it. I hope It will help you.
1. Bubble sorting
Basic idea:
Sort the array from back to front (reverse order) Perform multiple scans, and when it is found that the order of two adjacent values is inconsistent with the rules required for sorting, the two values are exchanged. In this way, the smaller (larger) values will gradually move from the back to the front.
<?php function mysort($arr) { for($i = 0; $i < count($arr); $i++) { $isSort = false; for ($j=0; $j< count($arr) - $i - 1; $j++) { if($arr[$j] < $arr[$j+1]) { $isSort = true; $temp = $arr[$j]; $arr[$j] = $arr[$j+1]; $arr[$j+1] = $temp ; } } if($isSort) { break; } } return $arr; } $arr = array(3,1,2); var_dump(mysort($arr)); ?>
2. Quick sort
Basic idea:
Select an element in the array (mostly the first ) as the ruler, scan the array once and sort the elements smaller than the ruler before the ruler, sort all the elements larger than the ruler after the ruler, and divide each subsequence into smaller sequences through recursion until all the sequences are in the same order. .
<?php //快速排序 function quick_sort($arr) { //先判断是否需要继续进行 $length = count($arr); if($length <= 1) { return $arr; } $base_num = $arr[0];//选择一个标尺 选择第一个元素 //初始化两个数组 $left_array = array();//小于标尺的 $right_array = array();//大于标尺的 for($i=1; $i<$length; $i++) { //遍历 除了标尺外的所有元素,按照大小关系放入两个数组内 if($base_num > $arr[$i]) { //放入左边数组 $left_array[] = $arr[$i]; } else { //放入右边 $right_array[] = $arr[$i]; } } //再分别对 左边 和 右边的数组进行相同的排序处理方式 //递归调用这个函数,并记录结果 $left_array = quick_sort($left_array); $right_array = quick_sort($right_array); //合并左边 标尺 右边 return array_merge($left_array, array($base_num), $right_array); } $arr = array(3,1,2); var_dump(quick_sort($arr)); ?>
Three, binary search
Basic idea:
Assume that the data is sorted in ascending order, for a given value x, starting from the middle position of the sequence, if the current position value is equal to x, the search is successful; if x is less than the current position value, the search is in the first half of the sequence; if x is greater than the current position value, the search is in the second half of the sequence Keep searching until you find it. (Use when the amount of data is large)
<?php //二分查找 function bin_search($arr,$low,$high,$k) { if($low <= $high) { $mid = intval(($low + $high)/2); if($arr[$mid] == $k) { return $mid; } else if($k < $arr[$mid]) { return bin_search($arr,$low,$mid-1,$k); } else { return bin_search($arr,$mid+1,$high,$k); } } return -1; } $arr = array(1,2,3,4,5,6,7,8,9,10); print(bin_search($arr,0,9,3)); ?>
4. Sequential search
Basic idea:
Start from the first position of the array An element is searched downwards one by one. If there is an element consistent with the target, the search is successful; if there is still no target element until the last element, the search fails.
<?php //顺序查找 function seq_search($arr,$n,$k) { $array[$n] = $k; for($i = 0;$i < $n; $i++) { if($arr[$i] == $k) { break; } if($i < $n) { return $i; } else { return -1; } } ?>
5. Write a function that can traverse all files and subfolders under a file
<?php function my_scandir($dir) { $files = array(); if($handle = opendir($dir)) { while (($file = readdir($handle))!== false) { if($file != '..' && $file != '.') { if(is_dir($dir."/".$file)) { $files[$file]=my_scandir($dir."/".$file); } else { $files[] = $file; } } } closedir($handle); return $files; } } var_dump(my_scandir('../')); ?>
6. Write a function that is as efficient as possible Get the file extension from a standard url
<?php function getExt($url) { $arr = parse_url($url);//parse_url解析一个 URL 并返回一个关联数组,包含在 URL 中出现的各种组成部分 //'scheme' => string 'http' (length=4) //'host' => string 'www.sina.com.cn' (length=15) //'path' => string '/abc/de/fg.php' (length=14) //'query' => string 'id=1' (length=4) $file = basename($arr['path']);// basename函数返回路径中的文件名部分 $ext = explode('.', $file); return $ext[count($ext)-1]; } print(getExt('http://www.sina.com.cn/abc/de/fg.html.php?id=1')); ?>
7. Method to intercept Chinese string without garbled characters
You can use mb_substr, but you need to ensure php_mbstring.dll is loaded in php.ini, that is, ensure that the line "extension=php_mbstring.dll" exists and is not commented out, otherwise undefined function problems will occur.
Related recommendations:
PHP implements bubble sorting, php bubble sorting
Bubble sorting in php, Rounding sort, insertion sort
The above is the detailed content of Commonly used bubble sorting & quick sorting algorithms and binary search & sequential search algorithm implementation in PHP. For more information, please follow other related articles on the PHP Chinese website!

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version
Visual web development tools
