2017-04-02 10 views
-1

Ich habe eine Zusammenführung Sortierung in Python, die funktioniert gut und ich habe versucht, die Logik in PHP neu zu erstellen, aber es funktioniert nicht richtig. Hier ist der Python-Code:PHP merge sort funktioniert nicht

def merge(array): 
    if len(array) > 1: 
     arrayL = [] 
     arrayR = [] 
     for i in range(int(len(array)/2)): 
      arrayL.append(array[i]) 
     for i in range(int(len(array)/2),len(array)): 
      arrayR.append(array[i]) 
     arrayL = merge(arrayL) 
     arrayR = merge(arrayR) 
     left = right = insert = 0 
     while left < len(arrayL) and right < len(arrayR): 
      if arrayL[left] < arrayR[right]: 
       array[insert] = arrayL[left] 
       left += 1 
      else: 
       array[insert] = arrayR[right] 
       right += 1 
      insert += 1 
     while left < len(arrayL): 
      array[insert] = arrayL[left] 
      left += 1 
      insert += 1 
     while right < len(arrayR): 
      array[insert] = arrayR[right] 
      right += 1 
      insert += 1 
    return array 

Und das ist aus der Schale:

>>> merge([23,21,5,111,32,11,7,1,45]) 
[1, 5, 7, 11, 21, 23, 32, 45, 111] 

Hier ist der PHP-Code:

function merge($array) { 
    $arrayLength = count($array); 
    if ($arrayLength > 1) { 
     $arrayLeft = array_slice($array, 0, $arrayLength/2); 
     $arrayRight = array_slice($array, $arrayLength/2); 
     $arrayLeft = merge($arrayLeft); 
     $arrayRight = merge($arrayRight); 
     $left = 0; 
     $right = 0; 
     $insert = 0; 
     while ($left < count($arrayLeft) and $right < count($arrayRight)){ 
      if ($arrayLeft[$left] < $arrayRight[$right]) { 
       $array[$insert] = $arrayLeft[$left]; 
       $left += 1; 
      } else { 
       $array[$insert] = $arrayRight[$right]; 
       $right += 1; 
      } 
      $insert += 1; 
     } 
     while ($left < count($arrayLeft)) { 
      $array[$insert] = $arrayLeft[$left]; 
      $left += 1; 
      $insert += 1; 
     } 
     while ($right < count($arrayRight)) { 
      $array[$insert] = $arrayRight[$right]; 
      $right += 1; 
      $insert += 1; 
     }  
     return $array; 
    } 

} 

print_r(merge(array(23,21,5,111,32,11,7,1,45))); 

Und das ist, was es gibt:

Array ([0] => 1 [1] => 5 [2] => 23 [3] => 21 [4] => 32 [5] => 11 [6] => 45 [7] => 45 [8] => 111) 

Jede Hilfe wäre sehr anerkennend ated

Antwort

1

Die return $array; Anweisung sollte außerhalb der if Bereich sein.

+0

Vielen Dank! Ich habe eine Stunde damit verbracht, dies zu beheben, ich kann nicht glauben, dass ich das nicht bemerkt habe – BeMu