Linear searching
One of the most common ways of performing a search is to compare each item with the one we are looking for. This is known as linear search or sequential search. It is the most basic way of performing a search. If we consider that we have n items in a list, in the worst case, we have to search n items to find a particular item. We can iterate through a list or array to find an item. Let's consider the following example:
function search(array $numbers, int $needle): bool { $totalItems = count($numbers); for ($i = 0; $i < $totalItems; $i++) { if($numbers[$i] === $needle){ return TRUE; } } return FALSE; }
We have a function named search
, which takes two arguments. One is the list of numbers, and the other is the number we are looking for in the list. We are running a for loop to iterate through each item in the list and compare them with our item. If a match is found, we return true and do not continue with the search. However, if the loop...