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()?
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.
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.