Home > Backend Development > PHP Tutorial > PHP bubble sort implementation code

PHP bubble sort implementation code

WBOY
Release: 2016-07-25 09:00:16
Original
1428 people have browsed it
Bubble sorting implemented with PHP code, friends in need can refer to it.

Bubble Sort(BubbleSort) Compare two adjacent numbers in sequence, placing the decimal in front and the large number in the back. That is, in the first pass: first compare the first and second numbers, put the decimal first and the large number last. Then compare the second number and the third number, put the decimal in front and the large number in the back, and continue like this until comparing the last two numbers, put the decimal in front and the large number in the back. This is the end of the first trip, leaving the largest number at the end. In the second pass: still start the comparison from the first pair of numbers (because it may be due to the exchange of the second number and the third number that the first number is no longer smaller than the second number), put the decimal first, and the large number After placing it, the comparison is continued until the second to last number (the first to last position is already the largest). At the end of the second pass, a new maximum number is obtained at the second to last position (in fact, it is the highest number in the entire sequence). The second largest number). Continue like this and repeat the above process until the sorting is finally completed. Friends who are interested can refer to the PHP bubble sorting example introduced by Programmer Home before.

Sample code:

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

    $arr=array(100,99,200,5,-4,6,-7);
    bubbleSort($arr);
    print_r($arr);   //数组是值传递,所以传递的时候加个&符号就是地址传递,改变外部变量
    //bbs.it-home.org
?>
Copy after login


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