Home > Backend Development > PHP Tutorial > PHP sorting bubble sort

PHP sorting bubble sort

小云云
Release: 2023-03-21 22:08:01
Original
1777 people have browsed it

When you are new to PHP, you usually use very few algorithms, but you still need to master several basic algorithms, such as bubble sorting. This article mainly shares with you the bubble sorting of PHP sorting, hoping to help everyone.

Requirements: Use bubble sorting method to sort the values ​​in the following arrays in ascending order.
Array to be sorted: $arr(1,34,555,63,21,66,32,78,36,76,25);
Idea analysis: The method is as its name suggests, just like bubbling, each time Pick the largest number from the array.

For example:
* 2,4,1 // The first bubble that pops up is 4
* 2,1,4 // The second bubble that pops up is 2
* 1,2,4 // In the end it became like this

<?php
/* 
 * 冒泡排序
 * 按照从小到的顺序进行排序
 * date 2017-1-20
 * author 疯狂老司机
 */
$arr=array(1,34,555,63,21,66,32,78,36,76,25);
function bubble_sort($arr)
{  
    $len=count($arr);
    //设置一个空数组 用来接收冒出来的泡
    //该层循环控制 需要冒泡的轮数
    for($i=1;$i<$len;$i++)
    { //该层循环用来控制每轮 冒出一个数 需要比较的次数
        for($k=0;$k<$len-$i;$k++)
        {
            if($arr[$k]>$arr[$k+1])
            {
                $tmp=$arr[$k+1];
                $arr[$k+1]=$arr[$k];
                $arr[$k]=$tmp;
            }
        }
    }
    return $arr;
}
?>
Copy after login


Related recommendations:

php bubble sort basic explanation

Detailed explanation of bubble sort in JavaScript

Js bubble sort and quick sort detailed explanation

The above is the detailed content of PHP sorting bubble sort. For more information, please follow other related articles on the PHP Chinese website!

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