pastebin

Paste Search Dynamic
Recent pastes
commonArray
  1. <?php
  2. //program to find the common elements of the two array
  3. //here we have to array A and B from which w have to find the common element
  4. //first we sort then using merge sort and after then for traversing through
  5. //the array in one iteration we can find the comman elements the given array
  6. //this is an inspace algorithm meansno extra space is needed
  7.  
  8. //best case time complexity=O(nlogn)
  9. //O(nlogn)-> for sorting
  10. //O(n)-> for while loop to find comman element
  11.  
  12. //average case time complexity=O(nlogn)
  13. //O(nlogn)-> for sorting
  14. //O(n)-> for while loop to find comman element
  15.  
  16. //worst case time complexity =O(nlogn)
  17. //O(nlogn)-> for sorting
  18. //O(n)-> for while loop to find comman element
  19.  
  20.  
  21.  
  22. $commonArray=array();
  23. $A=array(3,4,5,6,7,8,9,10,36,58,27,48);
  24. $B=array(3,10,4,5,6,8,12,24,37,27,50);
  25. sort($A);
  26. sort($B);
  27. $size1=sizeof($A);
  28. $size2=sizeof($B);
  29. $counter1=0;
  30. $counter2=0;
  31. while(($counter1< $size1) && ($counter2)<($size2))//traversing through the array
  32. {
  33.  
  34. if ($A[$counter1] == $B[$counter2])
  35. {
  36.       array_push($commonArray,$A[$counter1]);  //to enter comman element in the output array
  37.       $counter1=$counter1+1;
  38.       $counter2=$counter2+1;
  39. }
  40.     else if ($A[$counter1] < $B[$counter2])
  41. {
  42.      $counter1=$counter1+1; }
  43.  
  44.     else
  45. {
  46.      $counter2=$counter2+1;
  47. }
  48. }
  49.  
  50. print_r($commonArray);//to print the output array
  51. ?>
Parsed in 0.015 seconds