Home > Backend Development > PHP Tutorial > Bubble sorting PHP implementation java bubble sorting bubble sorting method bubble sorting c language code

Bubble sorting PHP implementation java bubble sorting bubble sorting method bubble sorting c language code

WBOY
Release: 2016-07-29 08:54:55
Original
1092 people have browsed it

<code><span>/**
 * 冒泡排序:稳定,时间复杂度 O(n^2)
 * 冒泡排序方法是最简单的排序方法。这种方法的基本思想是,
 * 将待排序的元素看作是竖着排列的“气泡”,较小的元素比较轻,
 * 从而要往上浮。在冒泡排序算法中我们要对这个“气泡”序列处理若干遍。
 * 所谓一遍处理,就是自底向上检查一遍这个序列,并时刻注意两个相邻的元素的顺序是否正确。
 * 如果发现两个相邻元素的顺序不对,即“轻”的元素在下面,就交换它们的位置。
 * 显然,处理一遍之后,“最轻”的元素就浮到了最高位置;处理二遍之后,“次轻”的元素就浮到了次高位置。
 * 在作第二遍处理时,由于最高位置上的元素已是“最轻”元素,所以不必检查。
 * 一般地,第i遍处理时,不必检查第i高位置以上的元素,因为经过前面i-1遍的处理,它们已正确地排好序。
 *<span> @param</span> array $arr
 *<span> @return</span> array
 */</span><span><span>function</span><span>bubbleSort</span><span>(array <span>$arr</span>)</span>{</span><span>$count</span> = count(<span>$arr</span>);
    <span>if</span>(<span>$count</span> > <span>1</span>){
        <span>//表示要跑N趟</span><span>for</span> (<span>$i</span>=<span>0</span>;<span>$i</span><<span>$count</span>;<span>$i</span>++){
            <span>//表示每趟要比较的次数</span><span>//比较完一次后,最大的数就到了最右边,就可以少比较一次,所以要减去$</span><span>for</span> (<span>$j</span>=<span>$i</span>+<span>1</span>;<span>$j</span><<span>$count</span>- <span>$i</span> - <span>1</span>;<span>$j</span>++){
                <span>if</span>(<span>$arr</span>[<span>$j</span>] > <span>$arr</span>[<span>$j</span> + <span>1</span>]){
                    <span>$temp</span> = <span>$arr</span>[<span>$j</span>];
                    <span>$arr</span>[<span>$j</span>] = <span>$arr</span>[<span>$j</span> + <span>1</span>];
                    <span>$arr</span>[<span>$j</span> + <span>1</span>] = <span>$temp</span>;
                }
            }
        }
    }<span>else</span>{
        <span>return</span><span>$arr</span>;
    }
}</code>
Copy after login
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above introduces the PHP implementation of bubble sorting, including bubble sorting and PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.

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