Home Backend Development PHP Tutorial Commonly used bubble sorting & quick sorting algorithms and binary search & sequential search algorithm implementation in PHP

Commonly used bubble sorting & quick sorting algorithms and binary search & sequential search algorithm implementation in PHP

Aug 22, 2018 pm 04:34 PM

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));
?>
Copy after login

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));
?>
Copy after login

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));
?>
Copy after login

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;
}
}
?>
Copy after login

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 != &#39;..&#39; && $file != &#39;.&#39;)
{
if(is_dir($dir."/".$file))
{
$files[$file]=my_scandir($dir."/".$file);
}
else
{
$files[] = $file;
}
}
}
closedir($handle);
return $files;
}
}
var_dump(my_scandir(&#39;../&#39;));
?>		
Copy after login

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 中出现的各种组成部分
//&#39;scheme&#39; => string &#39;http&#39; (length=4)
//&#39;host&#39; => string &#39;www.sina.com.cn&#39; (length=15)
//&#39;path&#39; => string &#39;/abc/de/fg.php&#39; (length=14)
//&#39;query&#39; => string &#39;id=1&#39; (length=4)
$file = basename($arr[&#39;path&#39;]);// basename函数返回路径中的文件名部分
$ext = explode(&#39;.&#39;, $file);
 return $ext[count($ext)-1];
}
print(getExt(&#39;http://www.sina.com.cn/abc/de/fg.html.php?id=1&#39;));
?>
Copy after login

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!

Statement of this Website
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

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

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

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.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

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? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

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 permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

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...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

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�...

See all articles