tags:

views:

40

answers:

1

How would I write an efficient algorithm to search for a subset array of integers in another array in C? For example:

unsigned a[] = {42, 72, 61, 1023, 84, 42, 42, 193, 302, 72};
unsigned long al = 10;
unsigned b[] = {61, 1023, 84};
unsigned long bl = 3;

I've tried a brute-force approach, by looping through a and then looping through b if a[n] is b[0], but then backtracking if the match fails halfway. It seems like the best I can think of, but I'm sure there must be a faster way.

+6  A: 

There are several well-known, efficient string searching algorithms and they will all work for this purpose. There's really no difference between an array of integers and an array of integers which have each been assigned to character representations if a subsequence is what you're looking for.

If your problem is really a small as what you've posted, it's probably not worth using anything except brute force, but I'm assuming that's just a toy example of what you want to do.

Tyler McHenry
Thanks for that! Sorry about not finding what was so close to me.
Delan Azabani