The Big O designation is all approximations. This simplifies the comparison of algorithms.
If you present your array of elements, the search can be in order N (you have to look at each element to find the element you need), it can be Log (N) order, if you have an ordered collection, or it can even be in order 1 depending on the type of your collection.
It is important to look at your algorithm and determine which key operations are repeated.
Foreach is obviously an operation of order N, by definition you should work with every element of your list. O (N)
Next is your if InArray 2. This is similar to searching through an array, which is likely to be unordered, so this will be order N (linear search). So your complexity will now be O (N * M). (for each n elements in array 1, search for complexity of order N in array 2).
Finally, you have an array. I do not know your environment, but it can be order 1 or order N, if the array needs to be redistributed and copied in order to grow. Let's assume order 1 is simple. So your complexity in Big O is O (N * M).
So, now it is best that each element finds it in the first attempt and performs a push of the array, which will be O (N * 1 * 1) = O (N).
In the worst case, each element cannot be found in the second list, forcing a complete search for all elements of array 2. Therefore, the complexity is O (N * M).
Your teachers want to understand your thinking, so show them your assumptions. I strongly recommend that you read the exact question and the information that was provided to you before relying on the assumptions given here, you may have been told a language / platform that will tell you the exact punishment and the algorithms used in each case. Hope that helps :)
Spence
source share