2017-04-24 3 views
1

PHPを使用して、配列の選択ソートを実行したいと思います。しかし、左から右に動かす代わりに、右から左に動かしたいと思っています。 Example of LogicPHPの逆選択ソート

$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はループのデクリメントを使用してこれを組み込むことを試みました。しかし、配列を部分的にソートするだけです。

+0

予想通り、それは何をあなたは右または左へ、左から右に意味するか、そしてあなたがのために行く何の成果教えてくださいすることができます動作します – user2860957

答えて

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