The four classic sorting algorithms in PHP
1. Bubble sorting
Idea analysis: In a set of numbers to be sorted, for the currently unsorted sequence, sort the two adjacent ones from front to back The numbers are compared and adjusted in turn, so that the larger numbers sink and the smaller numbers rise. That is, whenever two adjacent numbers are compared and it is found that their ordering is opposite to the ordering requirement, they are swapped.
Code implementation:
$arr=array(1,43,54,62,21,66,32,78,36,76,39); function bubbleSort($arr) { $len=count($arr); //该层循环控制 需要冒泡的轮数 for($i=1;$i<$len;$i++) { //该层循环用来控制每轮 冒出一个数 需要比较的次数 for($k=0;$k<$len-$i;$k++) { if($arr[$k]>$arr[$k+1]) { $tmp=$arr[$k+1]; $arr[$k+1]=$arr[$k]; $arr[$k]=$tmp; } } } return $arr; }
2. Selection sorting
Code implementation:
function selectSort($arr) { //双重循环完成,外层控制轮数,内层控制比较次数 $len=count($arr); for($i=0; $i<$len-1; $i++) { //先假设最小的值的位置 $p = $i; for($j=$i+1; $j<$len; $j++) { //$arr[$p] 是当前已知的最小值 if($arr[$p] > $arr[$j]) { //比较,发现更小的,记录下最小值的位置;并且在下次比较时采用已知的最小值进行比较。 $p = $j; } } //已经确定了当前的最小值的位置,保存到$p中。如果发现最小值的位置与当前假设的位置$i不同,则位置互换即可。 if($p != $i) { $tmp = $arr[$p]; $arr[$p] = $arr[$i]; $arr[$i] = $tmp; } } //返回最终结果 return $arr; }
3.Insertion sorting
Idea analysis: In a set of numbers to be sorted, suppose The previous numbers are already in order. Now we need to insert the n-th number into the previous ordered numbers so that these n numbers are also in order. Repeat this cycle until everything is in order.
Code implementation:
function insertSort($arr) { $len=count($arr); for($i=1, $i<$len; $i++) { $tmp = $arr[$i]; //内层循环控制,比较并插入 for($j=$i-1;$j>=0;$j--) { if($tmp < $arr[$j]) { //发现插入的元素要小,交换位置,将后边的元素与前面的元素互换 $arr[$j+1] = $arr[$j]; $arr[$j] = $tmp; } else { //如果碰到不需要移动的元素,由于是已经排序好是数组,则前面的就不需要再次比较了。 break; } } } return $arr; }
4. Quick sort
Idea analysis: Select a benchmark element, usually the first element or the last element. Through one scan, the column to be sorted is divided into two parts, one part is smaller than the reference element, and the other part is greater than or equal to the reference element. At this time, the base element is at its correct position after sorting, and then the two divided parts are sorted recursively in the same way.
Code implementation:
function quickSort($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); }
The above is the detailed content of The four classic sorting algorithms 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

AI Hentai Generator
Generate AI Hentai for free.

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

This article will introduce how to sort pictures according to shooting date in Windows 11/10, and also discuss what to do if Windows does not sort pictures by date. In Windows systems, organizing photos properly is crucial to making it easy to find image files. Users can manage folders containing photos based on different sorting methods such as date, size, and name. In addition, you can set ascending or descending order as needed to organize files more flexibly. How to Sort Photos by Date Taken in Windows 11/10 To sort photos by date taken in Windows, follow these steps: Open Pictures, Desktop, or any folder where you place photos In the Ribbon menu, click

Outlook offers many settings and features to help you manage your work more efficiently. One of them is the sorting option that allows you to categorize your emails according to your needs. In this tutorial, we will learn how to use Outlook's sorting feature to organize emails based on criteria such as sender, subject, date, category, or size. This will make it easier for you to process and find important information, making you more productive. Microsoft Outlook is a powerful application that makes it easy to centrally manage your email and calendar schedules. You can easily send, receive, and organize email, while built-in calendar functionality makes it easy to keep track of your upcoming events and appointments. How to be in Outloo

Implementing filtering and sorting of XML data using Python Introduction: XML is a commonly used data exchange format that stores data in the form of tags and attributes. When processing XML data, we often need to filter and sort the data. Python provides many useful tools and libraries to process XML data. This article will introduce how to use Python to filter and sort XML data. Reading the XML file Before we begin, we need to read the XML file. Python has many XML processing libraries,

PHP development: How to implement table data sorting and paging functions In web development, processing large amounts of data is a common task. For tables that need to display a large amount of data, it is usually necessary to implement data sorting and paging functions to provide a good user experience and optimize system performance. This article will introduce how to use PHP to implement the sorting and paging functions of table data, and give specific code examples. The sorting function implements the sorting function in the table, allowing users to sort in ascending or descending order according to different fields. The following is an implementation form

In this problem, a string is given as input and we have to sort the words appearing in the string in lexicographic order. To do this, we assign an index starting from 1 to each word in the string (separated by spaces) and get the output in the form of sorted indices. String={"Hello","World"}"Hello"=1 "World"=2 Since the words in the input string are in lexicographic order, the output will print "12". Let's look at some input/result scenarios - Assuming all words in the input string are the same, let's look at the results - Input:{"hello","hello","hello"}Result:3 Result obtained

In our work, we often use wps software. There are many ways to process data in wps software, and the functions are also very powerful. We often use functions to find averages, summaries, etc. It can be said that as long as The methods that can be used for statistical data have been prepared for everyone in the WPS software library. Below we will introduce the steps of how to sort the scores in WPS. After reading this, you can learn from the experience. 1. First open the table that needs to be ranked. As shown below. 2. Then enter the formula =rank(B2, B2: B5, 0), and be sure to enter 0. As shown below. 3. After entering the formula, press the F4 key on the computer keyboard. This step is to change the relative reference into an absolute reference.

How does Arrays.sort() method in Java sort arrays by custom comparator? In Java, the Arrays.sort() method is a very useful method for sorting arrays. By default, this method sorts in ascending order. But sometimes, we need to sort the array according to our own defined rules. At this time, you need to use a custom comparator (Comparator). A custom comparator is a class that implements the Comparator interface.

In this article, we will show you how to reorder multiple columns in PowerQuery by dragging and dropping. Often, when importing data from various sources, columns may not be in the desired order. Reordering columns not only allows you to arrange them in a logical order that suits your analysis or reporting needs, it also improves the readability of your data and speeds up tasks such as filtering, sorting, and performing calculations. How to rearrange multiple columns in Excel? There are many ways to rearrange columns in Excel. You can simply select the column header and drag it to the desired location. However, this approach can become cumbersome when dealing with large tables with many columns. To rearrange columns more efficiently, you can use the enhanced query editor. Enhancing the query
