Is it possible to improve this array intersection code

This is the minimum code to obtain arrays intersection without any repetition in the final array. Can it be improved ? I think it can't because it uses the minimum number of iteration thanks to the break in the inner loop and also that it can't be parallelized due to a critical section inside the if clause, am I wrong ? I tried to try this function and the Matlab one (intersect) with the same output and the latter is much faster, how is it possible ?

int intersection(int* array1, int* array2, int len1, int len2, int size) {
    int j, k, t, intersectC = 0;
    int* tmp = (int*)malloc(sizeof(int) * size);


    for (j = 0; j < len1; j++) {
        for (k = 0; k < len2; k++) {
            if (array1[j] == array2[k]) {
                    for (t = 0; t < intersectC; t++) {
                        if (tmp[t] == array1[j]) {
                            break;
                        }
                    }
                    if (t == intersectC) {
                        tmp[intersectC++] = array1[j];
                    }
                }
            }
        }

    free(tmp);
    return intersectC;
}

P.S. size is the greatest between len1 and len2



from Recent Questions - Stack Overflow https://ift.tt/3cUEatv
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Hibernate Search - Elasticsearch with JSON manipulation

Spring Elasticsearch Operations