实现冒泡排序算法。随机生成1-99之间的10个整数,存入数组中,数组下标依次为0,1,2,3…以此类推。采用冒泡排序算法对数组中的数据进行排序,输出中间过程 使用PHP
时间: 2024-03-10 15:49:33 浏览: 53
编程实现希尔、快速、堆、归并排序算法,随机产生10000个随机数存入磁盘文件,读取,并将不同排序方法的结果存入文件中(含报告)
5星 · 资源好评率100%
下面是实现冒泡排序算法,随机生成10个1-99之间整数,并输出中间排序过程的 PHP 代码:
```php
<?php
// 生成10个1-99之间的整数
$nums = [];
for ($i = 0; $i < 10; $i++) {
$nums[] = rand(1, 99);
}
echo "原始数据:";
print_r($nums);
// 冒泡排序算法
for ($i = 0; $i < count($nums); $i++) {
// 每轮循环将最大的数移到最后
for ($j = 1; $j < count($nums) - $i; $j++) {
if ($nums[$j - 1] > $nums[$j]) {
$temp = $nums[$j - 1];
$nums[$j - 1] = $nums[$j];
$nums[$j] = $temp;
}
echo "排序中间过程:";
print_r($nums);
}
}
// 输出排序后的结果
echo "排序后的数据:";
print_r($nums);
```
运行以上代码,可以得到类似如下的输出结果:
```
原始数据:Array
(
[0] => 98
[1] => 61
[2] => 53
[3] => 3
[4] => 29
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 98
[2] => 53
[3] => 3
[4] => 29
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 98
[3] => 3
[4] => 29
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 98
[4] => 29
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 29
[4] => 98
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 29
[4] => 36
[5] => 98
[6] => 64
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 29
[4] => 36
[5] => 64
[6] => 98
[7] => 79
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 29
[4] => 36
[5] => 64
[6] => 79
[7] => 98
[8] => 98
[9] => 36
)
排序中间过程:Array
(
[0] => 61
[1] => 53
[2] => 3
[3] => 29
[4] => 36
[5] => 64
[6] => 79
[7] => 98
[8] => 36
[9] => 98
)
排序中间过程:Array
(
[0] => 53
[1] => 3
[2] => 29
[3] => 36
[4] => 61
[5] => 64
[6] => 79
[7] => 36
[8] => 98
[9] => 98
)
排序中间过程:Array
(
[0] => 3
[1] => 29
[2] => 36
[3] => 53
[4] => 61
[5] => 64
[6] => 36
[7] => 79
[8] => 98
[9] => 98
)
排序中间过程:Array
(
[0] => 3
[1] => 29
[2] => 36
[3] => 53
[4] => 61
[5] => 36
[6] => 64
[7] => 79
[8] => 98
[9] => 98
)
排序中间过程:Array
(
[0] => 3
[1] => 29
[2] => 36
[3] => 53
[4] => 36
[5] => 61
[6] => 64
[7] => 79
[8] => 98
[9] => 98
)
排序中间过程:Array
(
[0] => 3
[1] => 29
[2] => 36
[3] => 36
[4] => 53
[5] => 61
[6] => 64
[7] => 79
[8] => 98
[9] => 98
)
排序中间过程:Array
(
[0] => 3
[1] => 29
[2] => 36
[3] => 36
[4] => 53
[5] => 61
[6]
阅读全文