首页 > 解决方案 > PHP:比较和交换计数

问题描述

我在 PHP 中有一个任务:我需要创建 100 个“Collat​​z”列表(从 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];
}
?>

这是具有“collat​​z”创建和冒泡排序的函数文件:在冒泡排序函数中,我获取计数器数组及其索引并尝试将计数存储在每个索引中。

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,这不起作用,我找不到解决方案,帮帮我!

标签: php

解决方案


您的外部循环需要提前 1 步终止。

冒泡排序通过比较相邻对的列表,即索引[(0,1), (1,2), ... ],并且在第一次迭代中,这必须到达最后一对(maxIndex - 1, maxIndex)

您的实现将这些对表示为 index$j和处的值$j + 1,但目前$j + 1将超出范围。

TLDR: 设置$n = sizeof($arr) - 1,并更改内部循环以在何时终止$j < $n - $i


推荐阅读