search
HomeBackend DevelopmentPHP TutorialHow to implement array sorting in PHP: quick sort, insertion sort, merge sort algorithm

There are many ways to sort arrays in php, and each array sorting has its own different principles. Let’s take a closer look at the examples of quick sort algorithm, merge sort algorithm and insertion sort algorithm.

Traversal of special-shaped arrays

Find the average of the numbers in the following array:

$arr1 = array(
1, 2, array(31, 32, 33), 4,
array(51, 52, 53, array(541, 542, 543, 544) ),
6, array(71, 72, 73),
);
$count = 0; //计数
$sum = GetArraySum($arr1);
echo “\

Quick sort algorithm

Principle description:

For such an array: [5, 1,2, 6,7];

Take out the first item (and use it as the intermediate array), and After comparing the remaining items, they are divided into two arrays:

The left array item is smaller than the middle item, and the right array item is not smaller than the middle item.

If the left array and the right array are already sorted arrays, then merge the three to get the final result.

If the left array and the right array are not sorted arrays, continue to use this function recursively to obtain the ordered arrays.

Schematic diagram:

How to implement array sorting in PHP: quick sort, insertion sort, merge sort algorithm

Principal data:

$arr1 = [5, 2, 1, 6,7]; / /Data that effectively illustrates the principle 1

Small: [2, 1], Large: [6, 7], Middle: [5]

Combine the three: [1 , 2, 5, 6, 7];

$arr1 = [2, 1]; //Data that effectively illustrates the principle 2

Middle: [2], Left: [1] , []

Specific case:

$arr1 = [5, 2, 4, 6, 1, 3];
$arr1 = [5, 2, 4, 6, 1, 3];
//$arr1 = [5, 3, 2, 8, 7];
echo “\

Insertion sort algorithm

Principle description:

For such an array: [2 , 3, 4, 1];

To insert a certain number n into a sorted array,

Just add n followed by the item of the array from back to front In a comparison, as long as an item is found to be larger than n,

will move the item back one place, and then continue to take it out and compare it. If it is larger than n, move it back one place, and so on.

In the end, when there is nothing larger than n, put n into the position that was left empty when moving backward.

For an array, the first item can be regarded as an "already sorted" array,

then the second item can be "inserted sorted" according to the above principle, so the previous Two can be sorted,

and become a "sorted array" with two elements. This is followed by analogy.

Schematic diagram:

How to implement array sorting in PHP: quick sort, insertion sort, merge sort algorithm

Principle data:

$arr1 = [2, 3, 4, 1]; //Strong explanation Data of the principle 1

$arr1 = [2, 3, 1]; //Data that effectively illustrates the principle 2

$arr1 = [2, 1]; //Data that effectively illustrates the principle Data 3

$arr1 = [1, 2]; //Data 3

that effectively illustrates the principle:

$arr1 = [5, 2, 4, 6, 1, 3];
$arr1 = [2, 3, 4, 1];
$arr1 = [2, 4, 5, 6, 1, 3];
echo “\

Merge sort algorithm

Principle description:

For such an array: $arr1 = [1, 3, 5, 2, 4, 6]; divide it into two: $a = [1 , 3, 5],
$b = [2, 4, 6];

If there are two arrays that have been sorted, then after performing the following operations on the two arrays, You can get a sorted "fusion array" of the two arrays:

Take out the first item a1 of array a, then take out the first item b1 of array b, compare the sizes of a1 and b1,

Put the small one (assumed to be a1) into a new array, and delete the first item of the corresponding array a,

Then take out the first item of the corresponding array (not just now the data), and then continue to compare the sizes of the two

each time, put the smaller one into a new array, and continue the next "delete, fetch, compare". . . .

The final result is that you can get a new sorted array in the new array.

For an array that has not yet been sorted, as long as it is recursively divided into two, the shortest array will eventually be obtained - only one or 0 cells. This kind of array is naturally sorted. In good order.

Schematic diagram:

How to implement array sorting in PHP: quick sort, insertion sort, merge sort algorithm

Principle data:

$arr1 = [1, 3, 5, 4, 6, 7, 8 ]; //The data 1

that strongly illustrates the principle is divided into 2 from the middle: [ ]; [ 6, 7, 8]

[ 1, 3, 4, 5, ]

$arr1 = [1, 3, 2, 4]; //Data that effectively illustrates the principle 2

Demonstration case:


$arr1 = [5, 2, 4, 6, 1, 3];
echo “\

Related recommendations:

php bubble sort quick sort, php bubble sort

php array sorting method sharing (bubble sort, selection Sort)

The above is the detailed content of How to implement array sorting in PHP: quick sort, insertion sort, merge sort algorithm. 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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.