Home > php教程 > php手册 > body text

PHP实现冒泡排序,php冒泡排序

WBOY
Release: 2016-06-13 08:38:59
Original
1068 people have browsed it

PHP实现冒泡排序,php冒泡排序

1、首先我们必须弄清楚什么是冒泡排序,不理解冒泡排序的原理,我们就无法写出代码。

冒泡排序(BubbleSort)的基本概念是:依次比较相邻的两个数,将小数放在前面,大数放在后面。即在第一趟:首先比较第1个和第2个数,将小数放前,大数放后。然后比较第2个数和第3个数,将小数放前,大数放后,如此继续,直至比较最后两个数,将小数放前,大数放后。至此第一趟结束,将最大的数放到了最后。在第二趟:仍从第一对数开始比较(因为可能由于第2个数和第3个数的交换,使得第1个数不再小于第2个数),将小数放前,大数放后,一直比较到倒数第二个数(倒数第一的位置上已经是最大的),第二趟结束,在倒数第二的位置上得到一个新的最大数(其实在整个数列中是第二大的数)。如此下去,重复以上过程,直至最终完成排序。

PHP实现代码:

<?<span>php
    
    </span><span>//</span><span>冒泡排序方法</span>

    <span>function</span> bubblesort(&<span>$arr</span><span>){
            </span><span>//</span><span>定义一个变量保存交换的值</span>
        <span>$temp</span> =0<span>;
        </span><span>for</span>(<span>$i</span>=0;<span>$i</span><<span>count</span>(<span>$arr</span>);<span>$i</span>++<span>){
            
            </span><span>for</span>(<span>$j</span>=0;<span>$j</span><<span>count</span>(<span>$arr</span>)-<span>$i</span>-1;<span>$j</span>++<span>){
                        
                </span><span>if</span>(<span>$arr</span>[<span>$j</span>]><span>$arr</span>[<span>$j</span>+1<span>]){
                    </span><span>//</span><span>如果前面的那个数大于后面的那个数,那么他们就进行交换</span>
                    <span>$temp</span>=<span>$arr</span>[<span>$j</span><span>];
                    </span><span>$arr</span>[<span>$j</span>]=<span>$arr</span>[<span>$j</span>+1<span>];
                    </span><span>$arr</span>[<span>$j</span>+1]=<span>$temp</span><span>;
                }
            }            
        }
    }

    </span><span>$arr</span>=<span>array</span>(100,99,200,5,-4,6,-7<span>);
    bubbleSort(</span><span>$arr</span><span>);
    </span><span>print_r</span>(<span>$arr</span>);   <span>//</span><span>数组是值传递,所以传递的时候加个&符号就是地址传递,改变外部变量</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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!