Home > php教程 > php手册 > 冒泡排序-php,冒泡-php

冒泡排序-php,冒泡-php

WBOY
Release: 2016-06-13 09:17:53
Original
1046 people have browsed it

冒泡排序-php,冒泡-php

<span>PHP实现的代码先奉上:<br /><br />function</span> bubble_sort(<span>$array</span><span>) {
    </span><span>for</span> (<span>$i</span> = 0; <span>$i</span> < <span>count</span>(<span>$array</span>) - 1; <span>$i</span>++) {    <span>//</span><span>$i为已经排过序的元素个数</span>
        <span>for</span> (<span>$j</span> = 0; <span>$j</span> < <span>count</span>(<span>$array</span>) - 1 - <span>$i</span>; <span>$j</span>++) {    <span>//</span><span>$j为需要排序的元素个数,用总长减去$i</span>
            <span>if</span> (<span>$array</span>[<span>$j</span>] > <span>$array</span>[<span>$j</span> + 1]) {    <span>//</span><span>按升序排序</span>
                <span>$temp</span> = <span>$array</span>[<span>$j</span><span>];
                </span><span>$array</span>[<span>$j</span>] = <span>$array</span>[<span>$j</span> + 1<span>];
                </span><span>$array</span>[<span>$j</span> + 1] = <span>$temp</span><span>;
            }
        }
    }
    </span><span>return</span> <span>$array</span><span>;
}<br /><br />$a = array(5, 1, 4, 7);<br /><br />代码执行过程:<br /></span>
Copy after login
<span>i = 0;<br />  j = 0;<br />  if($arr[0] > $arr[1]) => 5 > 1 条件成立,交换位置,形成新的数组 =>  1 5 4 7  j++<br />  if($arr[1] > $arr[2]) => 5 > 4 条件成立,交换位置, 形成新的数组 =>  1 4 5 7  j++ <br />  if($arr[2] > $arr[3]) => 5 > 7 条件不成立 ,数组保持不变 , 1 4 5 7 j++ j=3 退出内层循环, i++</span>
Copy after login
<span>依次类推吧。 <br /><br /><br /></span>
Copy after login
<span><br /><br /><br /></span>
Copy after login

 

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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template