Home > Article > Backend Development > 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:
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 '<pre class="brush:php;toolbar:false">'; var_dump($arr);
The final result is:
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!