2016-07-25 11 views
-2

Ich habe ein Array wie $ arr = Array (1,3,2,8,5,7,4,6,0);PHP-Array-Sortierung mit Bubble-Ansatz

Wie kann ich Blasensortiermethode für benutzerdefinierte Sortierung verwenden?

Danke

+0

http://stackoverflow.com/questions/9001294/bubble -sort-implementation-in-php – RomanPerekhrest

+4

1) Code schreiben 2) Code ausführen 3) Debug-Code. Wir helfen mit # 3. # 1-2 sind völlig in DEINE Verantwortung. –

Antwort

-4
$arr = array(7, 3, 9, 6, 5, 1, 2, 0, 8, 4); 
$sortedArr = bubbleSort($arr); 
var_dump($sortedArr); 

function bubbleSort(array $arr) { 
    $sorted = false; 
    while (false === $sorted) { 
     $sorted = true; 
     for ($i = 0; $i < count($arr)-1; ++$i) { 
      $current = $arr[$i]; 
      $next = $arr[$i+1]; 
      if ($next < $current) { 
       $arr[$i] = $next; 
       $arr[$i+1] = $current; 
       $sorted = false; 
      } 
     } 
    } 
    return $arr; 
} 

echo "<pre>"; 
print_r(bubbleSort($arr)); 

http://blog.richardknop.com/2012/06/bubble-sort-algorithm-php-implementation/

1

hier gehen Sie:

$a=array(5,4,3,1,2); 
for($j=0; $j < count($a)-1; $j++) { 
    $swapped=false; 
    $i=0; 
    while ($i < count($a)-1) { 
     if($a[$i] > $a[$i+1]) { 
      $c=$a[$i]; 
      $a[$i]=$a[$i+1]; 
      $a[$i+1]=$c; 
      $swapped=true; 
     } 
     ++$i; 
    } 

    if(!$swapped) 
     break; 
} 
print_r($a); 

Ausgänge:

Array 
(
    [0] => 1 
    [1] => 2 
    [2] => 3 
    [3] => 4 
    [4] => 5 
)