1. Bubbling algorithm
Search on the Internet a lot, but always for each cycle of the boundary value thinking is more general. is not very easy to be remembered by the novice, I myself usually also hard to write down. But for the algorithm, hard to remember, long time or easy to forget, so I wrote once, every thought as far as possible to write down, easy to understand, understand the easy to deepen the image, not easy to forget.
Bubble algorithm, the core is
Loop the size of each pair of 2 arrays adjacent to each other, and then put the largest array back, so that all the comparison loop once, will put the largest number of arrays in the array at the end,
Then repeat the loop (repeat the alignment loop above): At this time the last value of the loop is not required to participate in the loop, because it is determined to be the largest one. In other words, repeating loops is less than an array. Finally, there is only one array element left. End of cycle
At the code level,
$arr=array(5,4,3,6,7,1,2,10,8,9);
Let's start with the inner-layer cycle.
General for Loop so write
for($i= 0;$i<$xx;$i++){ if($arr[$i]>$arr[$i+1]) {//adjacent comparisons this should be easier to understand. $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; }}
The idea is that each cycle starts with the first element of the beginning so the $i start value is 0, repeats the loop once, and the next loop is less than an element. The $xx here is going to be smaller, so how can this $xx be sure?
First, let's look at this $xx boundary value.
$xx the first loop value is how much is the length of the array element count ($arr) minus 1 why? $arr[$i +1]. If the $xx equals the length of the array, each time the loop is compared to the last $arr [$i +1] does not exist, that is, no Fabienne.
What is the last value $xx? is 1, looping to the end with only one array element left.
That is, the $XX is count ($arr)-$k $k is the cumulative ratio of the loop to the (repeating loop once per loop)
for($i= 0;$i<Count($arr)-$k;$i++){ if($arr[$i]>$arr[$i+1]) {//adjacent comparison $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; }}
Look at this $k to think about this $k is the repetition of the cycle in the increase? Add the repeating loop code as follows
for($k= 1;$k<count ($arr);$k++){ //find the largest set of data with less length to float to the last for($i= 0;$i<count ($arr)-$k;$i++){ if($arr[$i]>$arr[$i+1]) {//adjacent comparison $tem=$arr[$i]; $arr[$i]=$arr[$i+1]; $arr[$i+1]=$tem; } } }
Let's see how $k determines the boundary value, $xx the boundary value is count ($arr)-1 to 1 has been defined so the mathematical algorithm $k the boundary value is also out of 1 to count ($arr) 1
Written into the loop is $k =1; $k <count ($arr); $k + +.
Language organization is still not perfect, wait until later to tidy up.
PHP Bubbling algorithm