I have been working with PHP for so long, and I have only used three kinds of sorting, bubble sorting, quick sorting, and barrel sorting. Let’s learn bubble sorting today:
So what is bubble sorting? Just like bubbles in a river, bubbles surface one by one, and here are numbers one by one. Its principle is to repeatedly visit (traverse) the sequence to be sorted and compare For two adjacent numbers, move the larger number to the right, and then traverse until all numbers complete the order from small to large. Each time the current maximum is compared, the remaining numbers are compared in the next round. Two loops are used to do this. The outer loop controls the number of rounds, and the inner loop controls the compared elements:
Upload the code
/** * 冒泡排序 */ $list = Array(6,8,7,2,3,4,1); echo "排序前"; print_r($list); function mao($arr){ for($i=1,$len=count($arr);$i<$len;++$i){ // 外层循环 数组个数-1 for($k=0,$klen=$len-$i;$k<$klen;++$k){ // 内层循环,比较两个数组元素 if($arr[$k]>$arr[$k+1]){ $temp = $arr[$k]; $arr[$k] = $arr[$k+1]; $arr[$k+1] = $temp; } } } return $arr; } echo "<br/>排序后"; print_r(mao($list));
In the process of bubbling, my ideas have been in other people’s thoughts. In the process of Baidu, I saw another method and thought it was good, so I wrote it:
$list = Array(6,8,7,2,3,4,1); echo "排序前"; print_r($list); function mao($arr){ for($i=0,$len=count($arr)-1;$i<$len;++$i){ // 外层循环 进行第一层遍历 // 内层循环,在外层的基础上加一,来控制两个元素的比较 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 "<br/>排序后"; print_r(mao($list));
During the writing process, I admired the latter way of writing very much. His thinking is very flexible, because the first way of writing is based on our normal thinking. It is very straightforward and I feel that the thinking is very interesting.