2017-04-24 6 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))); 
?>