Home > Backend Development > PHP Tutorial > PHP rearranges a set of numbers (bubble algorithm)

PHP rearranges a set of numbers (bubble algorithm)

藏色散人
Release: 2023-04-08 11:12:01
forward
2236 people have browsed it

PHP rearranges a set of numbers (bubble algorithm)

How to reorder the known array $arr = [24,69,80,57,13].

Idea:

1. We need to compare each two in the array before and after. If the front is smaller than the back, exchange the position;

2. Because it is Two-to-one comparison, so we need to compare count($arr) - 1 round, because after each round of comparison, a maximum value can be determined, so each round will be reduced once.

Illustration:

PHP rearranges a set of numbers (bubble algorithm)

Code:

//定义数组
$arr = [24,69,80,57,13];
//定义一个临时变量
$temp = 0;
//第一层循环,外层循环,循环count($arr) - 1 次(可以遍历到每一个数组值)
for ($i1=0; $i1 < count($arr); $i1++) { 
    //第二层循环,内层循环,每一次外层循环内,再次循环,循环次数依次减少一次(每次循环结束,可以获取到一个最大值)
    for ($i=0; $i < count($arr) - 1; $i++) {
        //判断条件,满足即交换值 
        if($arr[$i] > $arr[$i + 1]){
            //临时存储满足条件的变量值
            $temp = $arr[$i];
            //重新赋值
            $arr[$i] = $arr[$i + 1];
            //重新赋值
            $arr[$i + 1] = $temp;
        }
    }
}
//输出排列后的数组
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
var_dump($arr);
Copy after login

The final result is:

PHP rearranges a set of numbers (bubble algorithm)

For more related php knowledge, please visit php tutorial!

The above is the detailed content of PHP rearranges a set of numbers (bubble algorithm). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template