When you are new to PHP, you usually use very few algorithms, but you still need to master several basic algorithms, such as bubble sorting. This article mainly shares with you the bubble sorting of PHP sorting, hoping to help everyone.
Requirements: Use bubble sorting method to sort the values in the following arrays in ascending order.
Array to be sorted: $arr(1,34,555,63,21,66,32,78,36,76,25);
Idea analysis: The method is as its name suggests, just like bubbling, each time Pick the largest number from the array.
For example:
* 2,4,1 // The first bubble that pops up is 4
* 2,1,4 // The second bubble that pops up is 2
* 1,2,4 // In the end it became like this
<?php /* * 冒泡排序 * 按照从小到的顺序进行排序 * date 2017-1-20 * author 疯狂老司机 */ $arr=array(1,34,555,63,21,66,32,78,36,76,25); function bubble_sort($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; } ?>
Related recommendations:
php bubble sort basic explanation
Detailed explanation of bubble sort in JavaScript
Js bubble sort and quick sort detailed explanation
The above is the detailed content of PHP sorting bubble sort. For more information, please follow other related articles on the PHP Chinese website!