PHP and bubble sort

Ajouter un commentaire

Sorting algotithms are very conventional means  for handling a set of objects , which allow to obtain an ordered sequence of the objects. The method we present is to sort the table in as ascending order , by using the fact that at each step, all elements of the visited part of the table is actually a sequence of pairs that can be ordered. We do not merely clear the max for each scan, but the members of each pair being ordered. This may reduce the number of scans to be performed.

The bubble sort uses two nested loops.

The table is traversed by comparing adjacent elements of each pair, ie by ordering pairs of consecutive elements, if the second element of the box is smaller than of the previous, then exchange these two values for this pair is not well ordered. Note that any pair as the first element of the second preceding pair.
 It conducts courses on such prefixes in which the latter is avoided whenever, because it was well placed int the previous course.
After each course prefixes, the largest values in the table are the latest ski boxes, so that the largest element is systematically brought to the last box.
If no inversion is performend when scanning a prefix, it stops : the table is sorted, no inversion only occur on the following prefixes visited.

Here is the code of the function to be added to the class TableauReelTReel  of the former article.

// Tri par à bulles

  public function triBulle(){
   $indice = 0;
   $boolean = true;
   $nbIteration = count($this->tableauReel) - 1;
   while($boolean){
     $indice = 1;
     $boolean = false;
     while($indice <= $nbIteration) { 	
        if( $this->tableauReel[$indice] < $this->tableauReel[$indice-1]){
	   $this->echanger($indice, $indice-1);
	   $boolean = true;;
	}
      $indice++;
     }
   }
}
// Test Classe
$tableau = new TableauReelTReel();
$tableau->add(45);
$tableau->add(3.14);
$tableau->add(3.24);
$tableau->add(-1.14);
$tableau->add(4.14);
// Afficher tableau 
$tableau->afficher();
echo '
';
//$tableau->triMax();
$tableau->triBulle();
$tableau->afficher();

Overview of result code :

tribulles