


Commonly used bubble sorting & quick sorting algorithms and binary search & sequential search algorithm implementation in PHP
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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...
