php - PHP:比较和交换计数
问题描述
我在 PHP 中有一个任务:我需要创建 100 个“Collatz”列表(从 1 到 100),之后我需要使用冒泡排序对每个列表进行排序,然后计算我的每个列表的比较和交换次数分拣机。最后,我需要为每个列表打印比较和交换计数。我的问题是计算每种排序的比较和交换。
这是我的主文件: 对于每个计数器,我创建了一个数组并为它们创建了索引。
<?php
include 'func.php';
$collatz = array();
$bubble_equal_count=array(0);
$bubble_swap_count=array(0);
for($i=0;$i<=100;$i++)
{
$collatz[$i] = createCollatz($i);
echo "<pre>The original array is:<br>";
print_r($collatz[$i]);
echo "<br>The bubble sort array is:</br>";
bubbleSort($collatz,$bubble_equal_count,$bubble_swap_count,$equal_index,$swap_index);
selectionSort($collatz,$selection_equal_count,$selection_swap_count,$equal_index,$swap_index);
echo "<br>";
$equal_index+=1;
$swap_index+=1;
echo "equals=" . $bubble_equal_count[$equal_index];
echo "<br>";
echo "swaps=" . $bubble_swap_count[$swap_index];
}
?>
这是具有“collatz”创建和冒泡排序的函数文件:在冒泡排序函数中,我获取计数器数组及其索引并尝试将计数存储在每个索引中。
function createCollatz($n)
{
$collatz = array();
$i=0;
$collatz[$i]=$n;
while($n>1)
{
if($n&1)
$n=3*$n+1;
else
$n=$n/2;
$i++;
$collatz[$i]=$n;
}
return $collatz;
}
function bubbleSort($arr,&$bubble_equal_count,&$bubble_swap_count,$equal_index,$swap_index)
{
$n = sizeof($arr);
for($i = 0; $i < $n; $i++)
{
for ($j = 0; $j < $n - $i - 1; $j++)
{
$bubble_equal_count[$equal_index]++;
if ($arr[$j] > $arr[$j+1])
{
$bubble_swap_count[$swap_index]++;
$t = $arr[$j];
$arr[$j] = $arr[$j+1];
$arr[$j+1] = $t;
}
}
}
}
这是我得到的错误的一个例子:
The original array is:
Array
(
[0] => 3
[1] => 10
[2] => 5
[3] => 16
[4] => 8
[5] => 4
[6] => 2
[7] => 1
)
Notice: Undefined offset: 3 in C:\xampp\htdocs\collatz2\func.php on line 28
Notice: Undefined offset: 3 in C:\xampp\htdocs\collatz2\func.php on line 48
Notice: Undefined offset: 4 in C:\xampp\htdocs\collatz2\first.php on line 27
equals=
Notice: Undefined offset: 4 in C:\xampp\htdocs\collatz2\first.php on line 29
swaps=
Soo,这不起作用,我找不到解决方案,帮帮我!
解决方案
您的外部循环需要提前 1 步终止。
冒泡排序通过比较相邻对的列表,即索引[(0,1), (1,2), ... ],并且在第一次迭代中,这必须到达最后一对(maxIndex - 1, maxIndex)。
您的实现将这些对表示为 index$j
和处的值$j + 1
,但目前$j + 1
将超出范围。
TLDR:
设置$n = sizeof($arr) - 1
,并更改内部循环以在何时终止$j < $n - $i
推荐阅读
- c# - Entityframework为什么耦合表会得到重复值?
- symfony - 如何调试捆绑中的 DependencyInjection ?
- websphere - websphere application server 8.5.5 创建了很多到 ldap 的连接
- javascript - 到达带有锚点的页面时触发事件
- android-sqlite - 如果我的表有 4 列并且我想获取第三列我该怎么做。
- java - 在可穿戴设备上使用 FTP 主动模式时出现“网络无法访问”
- linux - sigreturn 如何在 SECCOMP_SET_MODE_STRICT 中阻止除 SIGKILL 和 SIGSTOP 之外的所有信号?
- sql - HIVE 计算列中值的数量并聚合
- python - content-type text/plain 的文件扩展名为 .ksh?
- java - 如何随机化 BitSet 的前 20 位跳过最低有效位?