泡沫,排序,策略

I am studying about bubble sorting strategy at php you can see the code Here, At the main loop, there is two condition need to be true so the loop will run, I understand that the variable is becouse we dont want our loop to run until its maximum iteration even the array is already sorted, but i did not understand why we need to check to see if we have got into the maximum iteration? why cant we just check the variable(My assumption is that we can have some problem at the variable and we dont want an eternal loop). any way i am not sure, i will be very thankful if some one can please tell me why we dont need to check only the variable at the the main loop, thank you all and have a nice day.

function sort(array &$vec)
    {
        $sorted = false;
        $size = sizeof($vec);
        for($i=0; $i<=$size-2 && !$sorted; $i++)
        {
            $maybeSorted = true;
            $from = 0;
            $till = $size-1-$i;
            for($j=$from; $j<$till; $j++)
            {
                if($vec[$j]>$vec[$j+1])
                {
                    $maybeSorted = false;
                    $temp = $vec[$j];
                    $vec[$j] = $vec[$j+1];
                    $vec[$j+1] = $temp;
                }
            }
            if($maybeSorted)
            {
                $sorted = true;
            }
        }
    }

You can check out this wikipedia link, there you can find the algorithem in pseudocode. Try to understand each step and start a new implemenation of it in your prefered laguage. This is the best way to learn sth. new!

Bubble sort does something like swap elements in each round and repeat this until there was nothing swapped in the last round.

UPDATE Some example for a good bubble sort algorithem:

function sort(array &$vec) {
  $n = sizeof($vec);

  do {
    $newn = 1;
    for ($i = 0; $i < ($n - 1); $i++) {
      if ($vec[$i] > $vec[$i + 1]) {
        $tmp         = $vec[$i];
        $vec[$i]     = $vec[$i + 1];
        $vec[$i + 1] = $tmp;
        $newn        = $i + 1;
      }
    }
    $n = $newn;
  } while ($n > 1);
}
  1. Get the number of elements in the array (we expect that nothing is sorted right now)
  2. Loop while there are elements $n that are not sorted so $n > 1
  3. In the for loop we go through the elements and check if they need to be swapped
  4. We do this till there is no element to swap so $n is not > 1

Example:

| 55 |  7 | 78 | 12 | 42 | 1. run
|  7 | 55 | 78 | 12 | 42 |
|  7 | 55 | 12 | 78 | 42 |
|  7 | 55 | 12 | 42 | 78 | last comparison
|  7 | 55 | 12 | 42 | 78 | 2. run
|  7 | 12 | 55 | 42 | 78 |
|  7 | 12 | 42 | 55 | 78 | last comparison (we now 78 is sorted!)
|  7 | 12 | 42 | 55 | 78 | 3. run
|  7 | 12 | 42 | 55 | 78 | sorted! (nothing was swapped)

(untested but should work) I hope this will help you.