There are many kinds of sorting involved in PHP, andBubble sortingis probably the most troublesome sorting I use. I still don’t understand it after doing it for a long time. This article briefly talks about PHP bubble sorting. The sorting is very suitable for people like me who don’t know much about bubble sorting!
1. Bubble algorithm
I have read several articles about bubbling, but always for eachloop# The boundary value idea of ## is relatively general.
It is not easy for novices to remember. I usually memorize it by heart. But for algorithms, it is easy to memorize them by heart, so it is easy to forget after a long time, so I wrote it once and tried to write down every idea as much as possible, so that it is easier to understand. Once you understand it, it will deepen your image and it will not be easy to forget. Bubble algorithm, the core is 1. Loop comparisonCompare the size of two adjacentarrayseach time, and then put the largest array At the end, if all comparisons are cycled once, the largest number in the array will be placed at the end of the array
2. Then repeat the cycle (repeat the above comparison cycle): when looping at this time The last value does not need to participate in the loop, because it has been determined to be the largest one. In other words,repeats the loop, and the comparison array becomes smaller and smaller. Finally there is only one array element left. End of loop
Look at the code level:$arr=array(5,4,3,6,7,1,2,10,8,9);
if($arr[$i]>$arr[$i+1]){//相邻比较 这个应该比较容易理解吧 $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; }
index, otherwise $arr[$i+1] does not exist and cannot be compared. That is to say, $i<count($ar)-1;$i’s initial value is 0
Let’s start with the inner comparison loop Generalfor loopWrite like this
for($i=0;$i<$xx;$i++){ if($arr[$i]>$arr[$i+1]){//相邻比较 这个应该比较容易理解吧 $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; } }
for($i=0;$i$arr[$i+1]){//相邻比较 $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; } }
for($k=1;$k$[$i+1]){ $temparr= $arr[$i]; $arr[$i] =$arr[$i+1]; $arr[$i+1] = $temparr; } } }
The above is the detailed content of Simple understanding of PHP bubble sort. For more information, please follow other related articles on the PHP Chinese website!