当前位置:网站首页>PHP common sorting algorithm
PHP common sorting algorithm
2022-07-03 07:45:00 【. Zhou Zhou】
1. Bubble sort
The basic idea : As shown in the figure below , Think of a set of data as a row of vertical bubbles , Then compare the last number with the penultimate number , Move the big one forward . And then in the same way , Compare the penultimate number with the penultimate number , Move the big one forward , By analogy , At the end of this cycle , The first element is the largest , And then the cycle goes on , Get a second , Third ……
function BubbleSort(&$arr){ // Must be &$arr, Send an address , If it is $arr, According to the function call mechanism , Sorting will not take effect
$temp = 0; // Intermediate variable
$flag = false;
// The outer cycle controls the number of cycles
for($i = 0; $i < count($arr) - 1; $i++) {
// The inner loop controls the exchange of each cycle
for($j = 0; $j < count($arr) - 1 - $i; $j++) {
if($arr[$j] > $arr[$j+1]) {
$temp = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $temp;
$flag = true;
}
}
if(!$flag)
break; // It's already orderly
$flag = false;
}
return $arr;
}2. Choose the sorting method
First , Compare the first one with all the others behind , Find the smallest number , Then swap with the first number ( Of course , If it is the first smallest , Then there is no need to exchange ), Then the cycle , namely : Compare the second with the latter , Find the smallest number , Then interchange with the second number , By analogy , That is to say, find out the minimum remaining value every time .
function selectSort(&$arr){
$temp = 0; // Intermediate variable
// The outer loop
for($i=0;$i<count($arr)-1;$i++){
// Hypothesis number 1 $i The number is the smallest number
// Record the value of the assumed minimum
$minVal=$arr[$i];
// Record the subscript of the lowest fraction of the hypothesis
$minIndex=$i;
for($j=$i+1;$j<count($arr);$j++){
// If the assumed minimum , Not the smallest
if($minVal>$arr[$j]){
$minVal=$arr[$j];
$minIndex=$j;
}
}
// Finally exchange
$temp=$arr[$i];
$arr[$i]=$arr[$minIndex]; // Outside of the loop , Cannot appear $j
$arr[$minIndex]=$temp;
}
return $arr;
}3. Insertion sort
The basic idea of insertion sorting is : In the set of numbers to sort , Suppose the previous numbers are already in order , Now let's put the n The number is inserted into the preceding ordinal number , Make this n The number is also in order . So repeatedly , Until it's all in order
function insertSort(&$arr){
// Default to the first number , That is, the subscript is 0 Number of numbers , It's already orderly
for($i=1;$i<count($arr);$i++){
// Number of ready inserts
$insertVal=$arr[$i];
// Ready to make peace first $insertIndex Compare
$insertIndex=$i-1;
while($insertIndex>=0 && $insertVal<$arr[$insertIndex]){
$arr[$insertIndex+1]=$arr[$insertIndex];
$insertIndex--;
}
$arr[$insertIndex+1]=$insertVal;
}
return $arr;
}4. Quick sort
Select a datum element , Usually select the first or last element . Through a scan , Divide the sequence to be arranged into two parts , Part smaller than the reference element , A part is greater than or equal to the datum element . At this time, the reference element is in the correct position after it is arranged , And then sort the two parts recursively in the same way .
function quickSort(&$arr) {
// First determine whether it is necessary to continue
$length = count($arr);
if($length <= 1) {
return $arr;
}
// Select the first element as the base
$base_num = $arr[0];
// Traverse all elements except the ruler , Put it into two arrays according to the size relationship
// Initialize two arrays
$left_array = array(); // Less than datum
$right_array = array(); // Greater than the benchmark
for($i=1; $i<$length; $i++) {
if($base_num > $arr[$i]) {
// Put it in the left array
$left_array[] = $arr[$i];
} else {
// Put it on the right
$right_array[] = $arr[$i];
}
}
// Then sort the arrays on the left and right in the same way, and call this function recursively
$left_array = quickSort($left_array);
$right_array = quickSort($right_array);
// Merge
return array_merge($left_array, array($base_num), $right_array);
}5. Exchange sort
Exchange sorting ideas : It is to exchange the positions of the two values in the sequence according to the comparison results of the two values in the array , The characteristics of exchange sorting are : Move the larger value towards the end of the array , Smaller values move towards the front of the array .
function exchangeSort($arr){
$len = count($arr);// Get array length
for ($i = 0;$i < $len - 1; $i++) {
for ($j = $i + 1; $j < $len; $j++) {
if ($arr[$j] < $arr[$i]) {
$iTemp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $iTemp;
}
}
}
return $arr;
}边栏推荐
- go语言-循环语句
- Pgadmin 4 v6.11 release, PostgreSQL open source graphical management tool
- 微软安全响应中心
- 技术干货 | AlphaFold/ RoseTTAFold开源复现(2)—AlphaFold流程分析和训练构建
- Es writing fragment process
- OSPF protocol summary
- Professor Zhang Yang of the University of Michigan is employed as a visiting professor of Shanghai Jiaotong University, China (picture)
- Screenshot tool snipaste
- Pat class a 1028 list sorting
- Go language foundation ----- 11 ----- regular expression
猜你喜欢

PAT甲级 1029 Median

Go language foundation ----- 15 ----- reflection

技术干货|昇思MindSpore可变序列长度的动态Transformer已发布!

【MindSpore论文精讲】AAAI长尾问题中训练技巧的总结
![[mindspire paper presentation] summary of training skills in AAAI long tail problem](/img/34/9c9ec1b94edeecd4a3e7f20fdd8356.png)
[mindspire paper presentation] summary of training skills in AAAI long tail problem

Harmonyos third training notes

Research shows that breast cancer cells are more likely to enter the blood when patients sleep

Go language foundation ----- 16 ----- goroutine, GPM model

技术干货|昇思MindSpore NLP模型迁移之Bert模型—文本匹配任务(二):训练和评估

Technical dry goods | Bert model for the migration of mindspore NLP model - text matching task (2): training and evaluation
随机推荐
Chapter VI - Containers
【LeetCode】2. Valid parentheses · valid parentheses
The babbage industrial policy forum
PAT甲级 1032 Sharing
Go language foundation ----- 06 ----- anonymous fields, fields with the same name
Go language - loop statement
【MySQL 14】使用DBeaver工具远程备份及恢复MySQL数据库(Linux 环境)
s7700设备如何清除console密码
Vertx multi vertical shared data
Lucene introduces NFA
PAT甲级 1028 List Sorting
Lucene merge document order
在浏览器输入url后执行什么
Technical dry goods | thinking about the unification of dynamic and static diagrams of AI framework
Technical dry goods | alphafold/ rosettafold open source reproduction (2) - alphafold process analysis and training Construction
opensips与对方tls sip trunk对接注意事项
Analysis of the problems of the 10th Blue Bridge Cup single chip microcomputer provincial competition
技术干货|昇思MindSpore初级课程上线:从基本概念到实操,1小时上手!
密西根大学张阳教授受聘中国上海交通大学客座教授(图)
[MySQL 11] how to solve the case sensitive problem of MySQL 8.0.18