PHP之冒泡排序

WBOY
Lepaskan: 2016-08-08 09:21:41
asal
833 orang telah melayarinya

昨天去酷狗面试的时候,在笔试那一关,有道要求用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>
Salin selepas log masuk

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

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

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!