search
HomeBackend DevelopmentPHP TutorialSummary of common sorting algorithms implemented in PHP, PHP sorting algorithm_PHP tutorial

A summary of common sorting algorithms implemented in php, php sorting algorithm

This article summarizes common PHP sorting algorithms, which has good reference value when designing algorithms. Now share it with everyone for reference. The details are as follows:

1. Insertion sort

Use text to describe simply, for example, $arr = array(4,2,4,6,3,6,1,7,9); Sort a group of numbers like this:
So, first, compare the second element of the array with the first element. If the first element is greater than the second element, then swap the positions of the two. Next, take the third element of the array and compare it with the first element. Two, the first element is compared, if the third element is smaller, then swap. And so on. This is insertion sort, and its time frequency is: 1+2+...+(n-1)=(n^2)/2. Then its time complexity is O(n^2).

php implementation code is as follows:

<&#63;php
function insertSort($arr){
   $count = count($arr);
   if($count<2){
  return $arr; 
   }
   for($i=1;$i<$count;$i++){
   $tmp = $arr[$i];
   $j=$i-1;
   while(j>=0&&$arr[$j]<$arr[$i]){
  $arr[$i] = $arr[$j];           
  $arr[$j] = $tmp;
  $j--;
   }
    }
    return $arr; 
 }
&#63;>

2. Selection sort

If the selection sorting is described in language, it can be like this, such as: $arr = array(4,3,5,2,1);

First, compare the first one with all the following ones, find the smallest number, and then exchange it with the first array (of course, if it is the first one that is the smallest, then there is no need to exchange it), and then loop , that is: compare the second number with the following number, find the smallest number, and then exchange it with the second number, and so on, that is to say, find the smallest remaining value each time. It can be obtained: the first time, the time frequency is n, (the first one is compared with the following n-1, find the smallest one, and then check whether it is the first one, if not, exchange it) in the future , followed by minus one. Its time complexity is also O(n^2);

php implementation code is as follows:

<&#63;php
function selectSort($arr){

   $count = count($arr);
   if($count<2){
  return $arr; 
   }
   for($i=0;$i<$count;$i++){
   $min=$i;
   for(j=$i+1;$j<$count;$j++){
  if($arr[$min]>$arr[$j]){
    $min = $j; //找到最小的那个元素的下标
  }
   }
   if($min!=$i){//如果下标不是$i 则互换。
   $tmp= $arr[$i];           
    $arr[$i] = $arr[$min];
    $arr[$min] = $tmp;
    }
    }
    return $arr; 
 }
&#63;>

3. Bubble sorting
 
There is actually no significant difference between bubble sort and selection sort. Find the smallest one and put it on the far left. Solve the problems in sequence. The difference is that bubble sorting swaps positions more times, while selection sorting finds the subscript of the smallest element, and then directly swaps positions with the leftmost element.


The php implementation code is as follows:

<&#63;php
function selectSort($arr){

   $count = count($arr);
   if($count<2){
  return $arr; 
   }
   for($i=0;$i<$count;$i++){
   for(j=$i+1;$j<$count;$j++){
  if($arr[$i]>$arr[$j]){
    $tmp= $arr[$i];           
    $arr[$i] = $arr[$i];
    $arr[$i] = $tmp;
  }
   }
    }
    return $arr; 
 }
&#63;>

4. Quick sort

Quick sort, to describe it in language, selects a value $a from the array, and then compares it with the other elements. The one larger than $a is placed in the array right, and vice versa, it is placed in the array left. Then recursively call left and right respectively, that is, subdivide left and right, and finally merge the arrays.

php quick sorting:

<&#63;php
function mySort($arr){

   $count = count($arr);
   if($count<2){
  return $arr; 
   }
   $key = $arr[0];//选择第一个元素作为比较元素,可选其他
    $left = array();       
    $right = array();
    for($i=1;$i<$count;$i++){
   if($key>=$arr[$i]){
  $left[] = $arr[$i]; 
   }else{
  $right[] = $arr[$i];
    }
    }
    $left = mySort($left);
    $right = mySort($right);
    $result = array_merge($left,$right);
    return $result; 
 }
&#63;>

5. Merge sort

In fact, merge sort is an idea of ​​splitting and merging. It has something in common with the idea of ​​quick sort, one pile on the left, one pile on the right, and then merged. Sorting is achieved through recursion. What's the difference? The difference between them is also an essential difference in thinking. The splitting of quick sort selects specific values ​​for size comparison, thus dividing them into left and right. That is, the small pile is placed on the left, and the large pile is placed on the right. Then, the small left is subdivided into left1 and right1. . . . Sorting is done by doing a similar recursion. In other words, if you keep subdividing it, left1 at the end of the recursion is the minimum value.

Merge sorting is to recursively divide the arrays from the left and right geometrically into the minimum granularity of 2 or 1, and then start to compare the sizes and then merge. The comparison size here is: the son's left element is compared with the son's right element, and then sorted and merged into the father's left or right. Here, until the last two arrays are sorted and merged respectively: the initial left and right, only their respective orders cannot be confirmed, and the order of the entire array cannot be confirmed. The merger still needs to be completed through the final comparison of left and right. Sorting in the truest sense.

<&#63;php
function gbSort($arr){
    if(count($arr)<=1){return $arr;}
    $min = floor(count($arr)/2);//取中间数字进行拆分
    $left = array_slice($arr,0,$min);
    $right = array_slice($arr,$min);
    $left = gbSort($left); //递归
    $right = gbSort($right);
    return get_merge($left,$right);//调用排序合并函数进行合并
}
function get_merge($left,$right){
    while(count($left) && count($right)){
        $m[] = $left[0]>$right[0] &#63; array_shift($right) : array_shift($left);
        //进行比较,小的移除,并且放入到数组$m中。
    }
    return arr_merge($m,$left,$right);//进行合并(由于不知道left right 哪个会为空,所以进行统一合并)
}

&#63;>

6. Heap sort

In this example, the fixDown function implements downward adjustment of a certain node. The default here is that the starting node is 1, which is convenient for calculating the relationship between parent and child nodes

Note:

The parent-child relationship with the starting node being 1: parent node k, child nodes are 2K, 2k+1 child node j, parent node is floor(j/2) floor is rounded down
The parent-child relationship with the starting node being 0: parent node k, child nodes are 2K+1, 2k+2 child node j, parent node is floor((j-1)/2)

The parameter $k is the adjustment point position, $lenth is the length of the array, which is the coordinates from 1 to the last node.

<&#63;php
function fixDown(&$arr, $k, $lenth)
{
  while(2*$k<=$lenth) { //只要当前节点有子节点, 就需要继续该循环
    $j = $k*2;
    if ($j<$lenth && $arr[$j]<$arr[$j+1]) $j++;  // 只要子节点有右节点,且右节点比左节点大,那么切换到右节点操作。
    if ($arr[$j] < $arr[$k]) break; // 如果子节点都没有父节点大, 那么调整结束。
    exch($arr[$j], $arr[$k]);
     $k = $j;
  }
}

function exch(&$a, &$b) {
  $tmp = $a; $a = $b; $b = $tmp;
}

function headSort(&$arr)
{
  $len = count($arr);
  array_unshift($arr, NULL);
  for($i=$len/2;$i>=1;$i--) {
    fixDown($arr, $i, $len);
  }
  while($len>1) {
    exch($arr[1], $arr[$len]);
    fixDown($arr, 1, --$len);
  }
  array_shift($arr);
}
$arr = array(4,6,4,9,2,3);
headSort($arr);
&#63;>

I hope the examples of sorting algorithms described in this article will be helpful to everyone’s PHP programming.

Use Java to implement several common sorting algorithms

Various sorting implemented in Java language, including insertion sort, bubble sort, selection sort, Shell sort, quick sort, merge sort, heap sort, SortUtil, etc.
Insertion sort: package org.rut.util.algorithm.support;
import org.rut.util.algorithm.SortUtil;/*** @author treeroot
* @since 2006-2-2
* @version 1.0*/public class InsertSort implements SortUtil.Sort{
/* (non-Javadoc)
* @see org.rut.util.algorithm.SortUtil.Sort#sort(int[]) */public void sort(int[] data) {int temp;for(int i=1;ifor(int j=i;(j0)&&(data[j] SortUtil.swap(data,j,j-1);}}}}Bubble sort: package org.rut.util.algorithm.support;
import org.rut.util.algorithm.SortUtil;/*** @author treeroot
* @since 2006-2-2
* @version 1.0*/public class BubbleSort implements SortUtil.Sort{
/* (non-Javadoc)
* @see org.rut.util.algorithm.SortUtil.Sort#sort(int[])*/public void sort(int[] data) {int temp;for( int i=0;ifor(int j=data.length-1;ji;j--){

What are the commonly used sorting algorithms?

Sorting algorithm The so-called sorting is the operation of arranging a string of records in increasing or decreasing order according to the size of one or some keywords in it.
Classification
Sorting algorithms used in computer science are usually classified as:
Computational complexity (worst, average, and best performance), according to the size of the list (n) . Generally speaking, good performance is O. (n log n), and the bad behavior is Ω(n2). The ideal performance for a sort is O(n). Sorting algorithms that use only one abstract key comparison always require at least Ω(n log n) on average.
Memory usage (and other computer resource usage)
Stability: A stable sorting algorithm maintains the relative order of records according to equal keys (in other words, values). That is to say, a sorting algorithm is stable, that is, when there are two records R and S with equal keys, and R appears before S in the original sequence, R will also be before S in the sorted sequence. Before.
General methods: insert, swap, select, merge, etc. Exchange sort includes bubble sort and quicksort. Selection sort includes shaker sort and heap sort.
When equal elements are indistinguishable, such as integers, stability is not an issue. However, assume that the following pairs of numbers are to be sorted by their first digit.
(4, 1) (3, 1) (3, 7) (5, 6)
In this case, it is possible to produce two different results. One is to maintain relative results based on equal key values. order, while the other one does not:
(3, 1) (3, 7) (4, 1) (5, 6) (maintain order)
(3, 7) (3, 1) (4 , 1) (5, 6) (Order changed)
Unstable sorting algorithms may change the relative order of records within equal key values, but stable sorting algorithms never do this. Unstable sorting algorithms can specifically be considered stable. One way to do this is to manually extend the key comparison, so that a comparison between two objects with otherwise identical keys is determined to use the entry in the original data order as a tiebreaker. However, keep in mind that this order usually involves additional space overhead.
List of sorting algorithms
In this table, n is the number of records to be sorted and k is the number of distinct key values.
Stable
Bubble sort — O(n2)
Cocktail sort (bidirectional bubble sort) — O(n2)
Insertion sort — O(n2)
Bucket sort — O(n); Requires O(k) additional memory
Counting sort — O(n+k); Requires O(n+k ) Extra memory
Merge sort — O(n log n); Requires O(n) extra memory
In-place merge sort — O(n2)
Binary tree sort ) — O(n log n); requires O(n) additional memory
Pigeonhole sort — O(n+k); requires O(k) additional memory
radix sort sort) — O(n·k); requires O(n) additional memory
Gnome sort — O(n2)
Library sort — O(n log n) with high probability, requires (1+ε) n extra memory
unstable
selection sort — O(n2)
shell sort — O(n log n) if using the best current version
Comb sort — O(n log n)
Heapsort — O(n log n)
...The rest of the text>>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/875872.htmlTechArticleA summary of common sorting algorithms implemented in PHP, PHP sorting algorithm This article summarizes common PHP sorting algorithms, and is doing algorithm design It has good reference value. Now share it with everyone for your reference...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool