I was given a task. Write an algorithm so that, the input of 2 lists of data, will have at least one in common.
So, this is my algorithm: (I write the code in php)
$arrayA = array('5', '6', '1', '2', '7');
$arrayB = array('9', '2', '1', '8', '3');
$arrayC = array();
foreach($arrayA as $val){
if(in_array($val, $arrayB)){
array_push($arrayC, $val);
}
}
Thats my own algo, not sure if its a good one. So, based on my algorithm, how to find the formula of best case and worst case (big O)?
Note: Please do let me know, if my algorithm is wrong. My goal is " input of 2 lists of data, will have at least one in common."
worst case can be found by assuming that both lists have an element in common and it's the last one on each list: this will lead to going through the first list by checking all elements of the second (you are using
in_array
but assume you do it by hand, it's the same thingO(m)
: complexity).So you are going
n
times through the second list, complexity will beO(n*m)
wheren
is the length of the first list andm
the length of the second..To find average complexity you should consider a solution that is average with respect to what you are computing.. it's quite easy and I leave it as an exercise.
When dealing with this kind of algorithmic problems you have to consider lists from an 'algorithmic' point of view. That is, a datatype with a little set of O(1) operations supported. Usually like below:
The idea is to express what is asked using only the above operators, then all you have to do is multiply the number of times a loop is executed by the complexity of what is inside it.
Be very careful when writing code in an evolved programming languages instead of writing an algorithm, as it hides complexity (@FrustratedWithFormsDesign allready hinted on this).
To get you started: