What’s a fastest way to implement array subtraction? For example:
array a1 = [1, 3, 4, 5, 8];
array a2 = [2, 4, 5];
array a3 = a1 - a2; /* [1, 3, 8] */
Here array would be the type my program uses to represent a struct which is used as a container. The rest of it is pseudo code, of course I’m not creating the arrays like that nor subtracting.
The simplest solution I can think of involves nested loops:
/* a1 - a2 */
for (i = 0; i < a1.size; ++i) {
int is_the_same = 0;
for (j = 0; i < a2.size; ++j)
if (a1[i] == a2[j]) {
is_the_same = 1;
break;
}
}
if (!is_the_same)
a3.push a1[i];
}
But this does not look very efficient. What would be another approach?
If your arrays aren’t sorted, the worst case time complexity for an array exclusion using a intuitive solution is O(n2) (although you can boost this if you sort the arrays first), since you need to check the whole array whether an element is existent or not.
Example of worst case scenario:
If your arrays are ordered, then the worst case time complexity is O(n+m) (pseudo-code):
UPDATE
-Wall -Wextra -pedanticC code:This will result in a worst time complexity of
O(n+m)for sorted arrays andO(n log n + m log m)for non-sorted arrays (sort both, use the function provided above).