Home > Backend Development > PHP Tutorial > PHP 数据结构 算法描述 冒泡排序 bubble sort_PHP

PHP 数据结构 算法描述 冒泡排序 bubble sort_PHP

WBOY
Release: 2016-06-01 12:16:31
Original
843 people have browsed it
复制代码 代码如下:
/**
* 冒泡排序 bubble sort
*
* 原理:多次循环进行比较,每次比较时将最大数移动到最上面。每次循环时,找出剩余变量里的最大值,然后减小查询范围。这样经过多次循环以后,就完成了对这个数组的排序
*/
function sort_bubble($list)
{
$len = count($list);
if(empty($len)) return $list;

for($i = 0;$i {
for($j = $i + 1; $j {
$flag = '';
if($list[$i] > $list[$j]) // 从小到大
//if($list[$i] {
$tmp = $list[$i];
$list[$i] = $list[$j];
$list[$j] = $tmp;

$flag = " change";
}
echo implode(',',$list).$flag."
";
}
echo "-------------------------
";
}
return $list;
}

$list = array(4,3,2,1,5,7,3,7);
$list = sort_bubble($list);
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