Search within an array and look for elements in a particular order

If arrays are very long, you will want to use an algorithm like Knuth-Morris-Pratt or maybe Boyer-Moore. (Look them up – they’re in any undergrad algorithms textbook)

If at least one of the arrays is short (say, 30 elements or less) it’s good enough to just loop through, brute force style.

(Note: I wired this up for illustration but haven’t actually tested it. The general idea is to iterate through each index in the longer array and then iterate from there through the shorter array to verify that each element matches; non-matches immediately stops iterating at that spot; matches all the way to the end stops all iterations and returns success with the index at which the subsequence was found.)

(And now someone will find that there’s actually a built-in subsequence finding function of some sort, which would be much more efficient – here’s hoping :smiley: )

1 Like