【问题标题】:PHP Reverse Selection SortPHP反向选择排序
【发布时间】:2017-09-20 14:09:39
【问题描述】:

我想使用 PHP 对数组进行选择排序。但不是让它从左向右移动,我希望它从右向左移动。 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)));

我试图通过使用递减的 for 循环来合并这一点。但它似乎只是对数组进行了部分排序。

【问题讨论】:

  • 从左到右或从右到左是什么意思,你能告诉你你想要什么结果

标签: php sorting selection reverse


【解决方案1】:

检查一下,它会按预期工作

<?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)));
?>

【讨论】:

    猜你喜欢
    • 2016-06-03
    • 2015-12-14
    • 1970-01-01
    • 2017-06-09
    • 1970-01-01
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2013-04-25
    相关资源
    最近更新 更多