Search/match algorithm between 2 vectors I have 2 vectors of Facebook-like pages which are represented by an ID from 2 different users. I want to verify the number of liked pages that are similar between these 2 users.

This is my algorithm that I am using right now, which is basically a search into all rows and columns of a matrix:

for(int i = 0; i &lt; 100; i++) {
 val = [user_like objectAtIndex:i];
 id like_user = [[val allValues] objectAtIndex:0];
 NSLog(@"like user %d is %@",i, like_user);

 for (int j = 0; j &lt; 100; j++) {

 val2 = [friend_like objectAtIndex:j];
 id like_friend = [[val2 allValues] objectAtIndex:2];
 NSLog(@"like friend %d is %@",j, like_friend);

 if (like_user == like_friend) {
 //do something
 }

 }

 }


How can I optimize this search/match algorithm?
Some problems with this code I want to address before I even get into optimization of speed.

First of all, there's absolutely no indentation, which makes this very hard to read.

Second of all, your variable names are both lacking, and not in keeping with Objective-C standard conventions.  Variable names like val and val2 aren't really descriptive enough.  A variable name like like_user may be descriptive enough (I don't know, it's borderline), but Objective-C standards suggest that the variable should instead be named likeUser.  We prefer camel casing to underscoring.

Next, you're using a for loop where you should be using a forin (I'll get to that later), but we're using the loop iterator as an index into an array... which is fine-ish... but you're concerning yourself with the array's length in the for's condition.  You're risking an index out of bounds exception.

But we really don't want to use a for loop anyway.  Any time we need to do something with each object in an Objective-C collection, we should use a forin loop anytime we can.  forin loops run faster than regular for loops--they're processed in batches.

But as 200_success points out, in this specific instance, we don't need to iterate through the indexes.

You stated you just want to count the number of common liked pages.

So, just as 200_success suggested:

NSSet *userLikeSet = [NSSet setWithArray:userLike];
NSMutableSet *commonLikeSet = [NSMutableSet setWithArray:friendLike];
NSSet *commonLikes = [commonLikeSet intersectSet:userLikeSet];

NSInteger commonLikeCount = [commonLikes count];