PHP and bubble sort

Sorting algorithms are very classical means of manipulating a set of objects to obtain an ordered sequence of these objects. The method we are going to present involves sorting the array in ascending order, using the fact that at each step, all elements in the visited part of the array actually form a sequence of pairs that can be ordered. We don’t just identify the maximum value at each pass, but we also sort the elements of each pair. This may eventually reduce the number of passes required.

Bubble sort uses two nested loops. The array is traversed by comparing adjacent elements in each pair, meaning by ordering consecutive pairs of elements: if the element in the second position is smaller than the one in the previous position, then we exchange these two values because this pair is not properly ordered. Note that each pair has the second element as the first element of the preceding pair.

Such traversals are performed on prefixes in which the last element is always avoided, as it has been correctly placed in the previous pass. After each pass of the prefixes, the largest values in the array will be moved to the last positions, ensuring that the largest element is consistently moved to the last position.

If no inversion occurs during the traversal of a prefix, we stop: the array is sorted, and no further inversions will occur in the subsequent visited prefixes.

This is the code for the function that needs to be added to the TableauReelTReel class from the previous article.

// Tri par à bulles
  public function triBulle(){
   $indice = 0;
   $boolean = true;
   $nbIteration = count($this->tableauReel) - 1;
     $indice = 1;
     $boolean = false;
     while($indice <= $nbIteration) { 	
        if( $this->tableauReel[$indice] < $this->tableauReel[$indice-1]){
	   $this->echanger($indice, $indice-1);
	   $boolean = true;;
// Test Classe
$tableau = new TableauReelTReel();
// Afficher tableau 
echo '

Code result preview