Searching array's item inside another array...

Mar 24, 2016 at 11:14pm
Hi,I am working on an algorithm to search an array inside of another array.

Example:

1
2
3
4
5
int first[5] = {1,2,3,4,5};
int second[15] = {0,0,0,0,0,1,2,3,4,5,0,0,0,0,0];

int index = Search(first,second);
cout << "The array's items are located between " << index << " and " << index + 5;


The program should be something like this,any idea about the function Search()?
Last edited on Mar 24, 2016 at 11:16pm
Mar 25, 2016 at 9:22am
It's quite simple. You first search for the first element of first in second. If you find it you need to compare the other 4 elements in first with the following in second.

Easier would be to use the search alogrithm in the std library.
http://www.cplusplus.com/reference/algorithm/search/
Mar 25, 2016 at 12:29pm
If the two arrays are large and speed matters then there are faster algorithms. Lookup substring match to find them.

The one I recall involves starting at the BACK of the substring. In your case it would go as follows:
- since first has 5 elements, you start by comparing first[4] to second[4]. They don't match.
- Since second[4] is a value that doesn't appear in first at all, you can skip your starting position all the way to second[5]. So you compare first[4] to second[9] and they match. Working backwards, you find that you've matched the string.
Topic archived. No new replies allowed.