douxu3315 2017-04-24 02:26
浏览 87

PHP反向选择排序

I would like to perform a selection sort of an array, using PHP. But instead of having it move from left to right, I would like it to move from right to left. Example of Logic

$array = array(3, 0, 2, 5, -1, 4, 1);

function swap($data1, $a, $b) {
  //Create temp storage for b
    $bTmp = $data1[$b];
  //Switch b for a value
    $data1[$b] = $data1[$a];
  //Set a as b value before switch
    $data1[$a] = $bTmp;
  //Return the sorted data
    return $data1;
}

function selection($data)
{
$i1=count($data)-1;
$j1=$i1-1;
//For each value in the array
for($i=$i1; $i>1; $i--) {
//Set the minimum as the current position
    $min = $i;
//Check the next value in the array (left)
    for($j=$j1; $j>0; $j--) {
//If the original value (i) is bigger than the next value...
        if ($data[$j]>$data[$min]) {
//Set the smaller value to be the next value
            $min = $j;
        }
    }
    $data = swap($data, $i, $min);
}

return $data;
}

//Perform the module using the array values and then output values with keys
echo(var_dump(selection($array)));

I have tried to incorporate this by using a decrementing for loop. But it only appears to partially sort the array.

  • 写回答

1条回答 默认 最新

  • dongnius85154 2017-04-25 08:47
    关注

    Check this, it will work as expected

    <?php
    $array = array(3, 0, 2, 5, -1, 4, 1);
    // $array = array(24,12,16,32,41,22);
    function swap($data1, $a, $b) {
        $bTmp = $data1[$b];
        $data1[$b] = $data1[$a];
        $data1[$a] = $bTmp;
        return $data1;
    }
    function selection($data)
    {
        $i1=count($data)-1;
        $j1 = $i1;
        foreach($data as $key => $val){
            for($i=$i1; $i>0; $i--) {
                $min = $i;
                $j1 = $min;
                for($j=$j1; $j>=0; $j--) {
                    if ($data[$j]>$data[$min]) {
                        $data = swap($data, $j, $min);
                        $min = $j;
                    }
                }
            }
        }
        return $data;
    }
    echo(var_dump(selection($array)));
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么