首頁  >  文章  >  後端開發  >  PHP之冒泡排序

PHP之冒泡排序

WBOY
WBOY原創
2016-08-08 09:21:41833瀏覽

昨天去酷狗面試的時候,在筆試那一關,有道要求用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> < <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> < <span>$in_loop_cnt</span>; <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>] < <span>$numbers</span>[<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教學有興趣的朋友有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn