首页 > 后端开发 > php教程 > PHP之冒泡排序

PHP之冒泡排序

WBOY
发布: 2016-08-08 09:21:41
原创
848 人浏览过

昨天去酷狗面试的时候,在笔试那一关,有道要求用PHP实现冒泡排序的编程题,因为实在太久没用过冒泡排序,忘记了算法的原理,结果留了空白,实在无语。因此今天把PHP的冒泡排序代码记录一下:

<code><span><?php </span><span>/**
 * 冒泡排序
 *<span> @param</span> array $numbers 要排序的数组,只限数字一维数组
 *<span> @param</span> boolean $asc   排序顺序,true是正序,false是逆序
 */</span><span><span>function</span><span>bubble_sort</span><span>(array <span>$numbers</span>, <span>$asc</span> = true)</span> {</span><span>$n</span> = count(<span>$numbers</span>);
    <span>// 外循环最多排(n - 1)次</span><span>$out_loop_cnt</span> = <span>$n</span> - <span>1</span>;
    <span>for</span> (<span>$i</span> = <span>0</span>; <span>$i</span> $out_loop_cnt</span>; <span>$i</span>++) {
        <span>// 内循环最多排(n - i - 1)次</span><span>$in_loop_cnt</span> = <span>$n</span> - <span>$i</span> - <span>1</span>;
        <span>for</span> (<span>$j</span> = <span>0</span>; <span>$j</span> $in_loop_cnt; <span>$j</span>++) {
            <span>// 根据排序顺序判断相邻两个数是否符合交换条件</span><span>$swap</span> = <span>$asc</span> ? (<span>$numbers</span>[<span>$j</span>] > <span>$numbers</span>[<span>$j</span> + <span>1</span>])
                : (<span>$numbers</span>[<span>$j</span>] $numbers[<span>$j</span> + <span>1</span>]);
            <span>if</span> (<span>$swap</span>) {
                <span>$temp</span> = <span>$numbers</span>[<span>$j</span> + <span>1</span>];
                <span>$numbers</span>[<span>$j</span> + <span>1</span>] = <span>$numbers</span>[<span>$j</span>];
                <span>$numbers</span>[<span>$j</span>] = <span>$temp</span>;
            }
        }
    }

    <span>return</span><span>$numbers</span>;
}

<span>$arr</span> = [<span>1</span>, <span>3</span>, <span>5</span>, <span>8</span>, <span>4</span>];

var_dump(bubble_sort(<span>$arr</span>));
<span>/**
 * 输出:
 * array (size=5)
 * 0 => int 1
 * 1 => int 3
 * 2 => int 4
 * 3 => int 5
 * 4 => int 8
 */</span>var_dump(bubble_sort(<span>$arr</span>, <span>false</span>));
<span>/**
 * 输出:
 * array (size=5)
 * 0 => int 8
 * 1 => int 5
 * 2 => int 4
 * 3 => int 3
 * 4 => int 1
 */</span></code>
登录后复制

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了PHP之冒泡排序,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板