|
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";
- Print_r ($list);
- Function Mao ($arr) {
- For ($i =1, $len =count ($arr), $i < $len, + + $i) {//Outer loop array number-1
- For ($k =0, $klen = $len-$i; $k < $klen; + + $k) {//inner loop, compare two elements of an array
- if ($arr [$k]> $arr [$k +1]) {
- $temp = $arr [$k];
- $arr [$k] = $arr [$k +1];
- $arr [$k +1] = $temp;
- }
- }
- }
- return $arr;
- }
- echo "
After sorting ";
- Print_r (Mao ($list));
Copy Code
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";
- Print_r ($list);
- Function Mao ($arr) {
- For ($i =0, $len =count ($arr)-1; $i < $len; + + $i) {//outer loop for first-level 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 ";
- Print_r (Mao ($list));
Copy Code
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,
|