0
<?php

$array=array('2','4','5','1','3');

echo "Unsorted array is: ";
echo "<br />";
print_r($array);


for($j = 0; $j < count($array); $j ++) {

    echo "#"; // prints '#' for 5 times

    for($i = 0; $i < count($array)-1; $i ++){

        echo "@"; // prints '@' 20 times

        if($array[$i] > $array[$i+1]) {
            $temp = $array[$i+1];
            $array[$i+1]=$array[$i];
            $array[$i]=$temp;
        }       
    }
}

echo "Sorted Array is: ";
echo "<br />";
print_r($array);

?>

Above is the code for sorting an array in ascending order using bubble sort. How to reduce the no of iterations while sorting an array in ascending order ?

I want to reduce the iterations of '@' symbol in inner loops!

Or can this sorting be done in minimum iterations ?

I do not want to use php in-built functions for sorting an array

Ruturaj
  • 21
  • 5
  • This question was already asked and answered in [Βubble sort array ,how can i make this php bubble sort code better or more effective?](http://stackoverflow.com/questions/37165951/%CE%92ubble-sort-array-how-can-i-make-this-php-bubble-sort-code-better-or-more-effec) – Luke Bajada Apr 08 '17 at 10:25
  • You implemented a "bubble sort" algorithm which does work, but is inefficient. I suggest you start reading a bit about different sorting algorithms, there is very good literature about that, since it is a well understood topic in computer science. – arkascha Apr 08 '17 at 10:27
  • I don't think my question was as same as http://stackoverflow.com/questions/37165951/%CE%92ubble-sort-array-how-can-i-make-this-php-bubble-sort-code-better-or-more-effec – Ruturaj Apr 08 '17 at 10:44
  • Possible duplicate of [How can I sort arrays and data in PHP?](http://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – Jörn Hees Apr 08 '17 at 12:48

0 Answers0