Contact PHP So long, also used three kinds of sort, bubble sort, quick sort, cask sort, today to learn about bubble sort:
So what is bubble sort, like a bubble in a river, a bubble emerges, and here is a number, and his principle is to repeat the sequence of visits (traversal) to sort, compare the number of adjacent two, move the large number to the right, and then traverse until all the numbers are completed from small to large. Each time compared to the current largest, the second round to compare the remaining number, with two cycles to do, the outer loop control wheel number, the inner layer loop control the elements of comparison:
On the Code
/** * Bubble Sort */$list = Array (6,8,7,2,3,4,1), echo "before sort";p rint_r ($list), Function Mao ($arr) {for ($i =1, $len =count ($arr); $i < $len + + $i) {//Outer loop array number -1for ($k =0, $klen = $len-$i; $k < $klen; + + $k) {//inner loop, compare two array elements if ($arr [$k]> $arr [$k +1]) { $temp = $arr [$k]; $arr [$k] = $arr [$k +1]; $arr [$k +1] = $temp;}}} return $arr;} echo "
After sorting ";p Rint_r (Mao ($list));
In the process of doing bubbles, the idea has been in the minds of others, in the process of Baidu, see another way, feel good also written over:
$list = Array (6,8,7,2,3,4,1), echo "before sort";p rint_r ($list), Function Mao ($arr) {for ($i =0, $len =count ($arr)-1; $i < $len; + + $i) {//outer loop for the first layer traversal//inner loop, plus one on the outer layer to control the comparison of two elements for ($k = $i +1; $k <= $len; + + $k) {if ($arr [$i]> $arr [$k]) {$temp = $arr [$i]; $arr [$i] = $arr [$k]; $arr [$k] = $temp;}}} return $arr;} echo "
After sorting ";p Rint_r (Mao ($list));
In the process of writing, I admire the latter kind of wording, his thinking is very flexible, because the first one is written according to our normal thinking in doing, very straightforward, feel that thinking is very interesting,
http://www.bkjia.com/PHPjc/762283.html www.bkjia.com true http://www.bkjia.com/PHPjc/762283.html techarticle Contact PHP So long, also used three sort, bubble sort, quick sort, cask sort, today to learn the bubble sort: Then what is bubble sort, like the gas in the river ...