Algorithm Action: Naive Search

Image for post
Image for post
Photo by Possessed Photography on Unsplash

Algos, algos, algos: the cornerstone of a competent software engineer. This is why I’m compiling all my research and work on the topic in a set of articles titled Algorithm Action.

Today, we’re checking out a specific sorting pattern known as naive search.

Naive search is more of a brute force method of finding strings inside of other strings, or any other problem like it, for example.

Naive search is pretty straightforward, using two for loops to go through each string and increment a matchCount as matches are found.

Let’s first define a function that takes two strings:

function naiveSearch(long, short) { }

Then, we’re going to loop over the long and short strings. If the characters do not match, break out of the inner loop. If they do, keep going. If the inner loop finishes, that means there’s a match. Increment matchCount.

function naiveSearch(long, short) {    let matchCount = 0;for (let i = 0; i < long.length; i++) { //looping over long                       string
for (let j = 0; j < short.length; j++) { //looping over short string
//if the short string's element is not the long string's
//element + 1, break out of loop
if (short[j] !== long[i + j]) {
break;
}
//if we find a whole match, the element's index
//will be the same, thus we increment matchCount
if (j === short.length - 1) {
matchCount++;
}
}
}
return matchCount;}

Thanks for reading!

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store