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 )

 

Find no of time a character used in string using PHP

  1. function char_in_string($string){
  2. $char_array=str_split($string);
  3. for($i=0;$i<sizeof($char_array);$i++){
  4. $no_of_char[$char_array[$i]]=0;
  5. for($j=0;$j<sizeof($char_array);$j++){
  6. if($char_array[$i]==$char_array[$j])
  7. {
  8. $no_of_char[$char_array[$i]]++;
  9. }
  10. }
  11. }
  12. return $no_of_char;
  13. }

 

Now show its structure using var_dump()

var_dump(char_in_string("Hello Ahmad Asjad"));

Its result will look something like this.

array (size=12)
  'H' => int 1
  'e' => int 1
  'l' => int 2
  'o' => int 1
  ' ' => int 2
  'A' => int 2
  'h' => int 1
  'm' => int 1
  'a' => int 2
  'd' => int 2
  's' => int 1
  'j' => int 1