MarioGT
MarioGT

Reputation: 682

Efficient Algorithm for comparing and iterate through two large arrays

I have this problem:

I want to iterate and compare each item of array1 against each item of array2, both arrays have the same lenght. When the value of both items coincide I store the value j in my indexOfInterest[] array for later use.

This is the code that I use, works well but its extremely slow comparing large arrays (thousands of items), can anyone help me in implement an efficient algorithm for this task.

int i,j;

int counter = [array1 count];

int indexOfInterest[counter];


for (i = 0; i < counter; i++) {

    for (j = 0; j < counter; j++) {

        if ([[array1 objectAtIndex:i] intValue] == [[array2 objectAtIndex:j]intValue] ) {

            indexOfInterest[i] = j;
        }
    }
}

Upvotes: 0

Views: 629

Answers (1)

Raunak
Raunak

Reputation: 3414

You can store the indices of array1 in a hashmap (NSDictionary) where the keys are the elements/values and the value is the index of that element (or array of indices if elements are allowed to repeat). Call it map_of_array1.

Then iterate through array2 and find if map_of_array1[array2[[i]] is not null.

This way your time complexity will be O(n+m) instead of O(n*m).

Upvotes: 2

Related Questions