Array Sorting With Single Loop

There is an unsorted array of integers. write the complete program to find the second largest no in the array without using sorting and max functions. You can only iterate(loop) over the array once.

 

 

  1. <?php
  2. echo "<br/>";
  3. $arr=array(12,52,2,35,95,17,37,42);
  4. echo "Before Sorting<br/>";
  5. print_r($arr);
  6. $tot_arr=count($arr);
  7. for($i=0;$i<$tot_arr;$i++){
  8. if(($i< ($tot_arr-1)) && $arr[$i]>$arr[$i+1]){
  9. $temp=$arr[$i];
  10. $arr[$i]=$arr[$i+1];
  11. $arr[$i+1]=$temp;
  12. $i=-1;
  13. }
  14. }
  15. echo "<br/>After Sorting<br/>";
  16. print_r($arr);
  17. ?>

 

 

Output:

 

Before Sorting
Array ( [0] => 12 [1] => 52 [2] => 2 [3] => 35 [4] => 95 [5] => 17 [6] => 37 [7] => 42 ) 
After Sorting
Array ( [0] => 2 [1] => 12 [2] => 17 [3] => 35 [4] => 37 [5] => 42 [6] => 52 [7] => 95 )

 

Binary Sorting Using PHP

CODE:

  1.  
  2. <?php
  3. $a = array();
  4. //get values to swap
  5. for($b=0;$b<10;$b++)
  6. {
  7.     $a[]=rand(99,999);
  8. }
  9. echo "<div style='float: left;margin-right: 20px;'>Before Sorting<br/>";
  10. for($b=0;$b<sizeof($a);$b++)
  11. {
  12.     echo $a[$b]."<br/>";
  13. }
  14. echo "</div>";
  15. //swap started
  16. for($i=0;$i<sizeof($a);$i++)
  17. {
  18.     for($j=0;$j<sizeof($a);$j++)
  19.     {
  20.         $swap="";
  21.         if($j<(sizeof($a)-1) && $a[$j]>$a[$j+1])
  22.         {
  23.             $swap=$a[$j];
  24.             $a[$j]=$a[$j+1];
  25.             $a[$j+1]=$swap;
  26.         }
  27.     }
  28. }
  29. echo "<div style='float: left;margin-right: 20px;'>After Sorting<br/>";
  30. for($b=0;$b<sizeof($a);$b++)
  31. {
  32.     echo $a[$b]."<br/>";
  33. }
  34. echo "</div>";
  35. echo "<div style='float: left;margin-right: 20px;'>In Descending Order<br/>";
  36. for($b=(sizeof($a)-1);$b>-1;$b--)
  37. {
  38.     echo $a[$b]."<br/>";
  39. }
  40. echo "</div>";
  41. ?>
  42.  

 

OUTPUT:

Before Sorting
831
507
410
677
970
838
748
705
206
978
After Sorting
206
410
507
677
705
748
831
838
970
978
In Descending Order
978
970
838
831
748
705
677
507
410
206