PHP反向选择排序

时间:2017-04-24 02:26:48

标签: php sorting selection reverse

我想使用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)));

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

1 个答案:

答案 0 :(得分:0)

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

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