81,641 views
17 votes
17 votes
Why don't we use a for each loop when doing a sequential (linear) search?

User Floris
by
2.9k points

1 Answer

8 votes
8 votes

Answer:Linear search (aka Sequential Search) is the most fundamental and important of all algorithms. It is simple to understand and implement, yet there are more subtleties to it than most programmers realize.

The input to linear search is a sequence (e.g. an array, a collection, a string, an iterator, etc.) plus a target item. The output is true if the target item is in the sequence, and false otherwise. If the sequence has n items, then, in the worst case, all n items in the sequence must be checked against the target for equality. Under reasonable assumptions, linear search does O(n) comparisons on average. In practice, this is often too slow, and so, for example, BinarySearching or hashing or TreeSearching are speedier alternatives.

Here's an implementation of linear search on an array (in Java):

Step-by-step explanation:

User Uppi
by
3.2k points