php bubble sort_PHP tutorial

WBOY
Release: 2016-07-13 10:31:32
Original
804 people have browsed it

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));
Copy after login

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));
Copy after login

 

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/762283.htmlTechArticleI have been exposed to PHP for so long, and I have only used three kinds of sorting, bubble sorting, quick sorting, and barrel sorting. , let’s learn about bubble sort today: So what is bubble sort, just like the air in the river...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!