Searching Algorithms |
Determining whether an element is included within a collection is a common task. Indeed, most collection-type classes offer a contains() method for this very reason. There are two common strategies (algorithms) for searching a collection for a given element: the sequential search and the binary search.
The Sequential (Linear) Search.
In the sequential search, inspection begins with the first element and proceeds until the element is found or the end of the collection is encountered. If the element if found, typically the algorithm returns the position of index of the location in the collection. If the element is not found, a value of -1 is returned.
The Binary Search.