Searching Algorithm
In one line
A searching algorithm finds the position (or existence) of a target value within a collection of data.
In simple words
A searching algorithm locates a specific value in a data structure. The simplest is linear search: check each element one by one — O(n) time, works on any list. For sorted data, binary search is much faster: repeatedly halve the search range — O(log n) time.
The choice of search depends on the data and how often you search. If you search once on unsorted data, linear search is fine. If you search many times, sort once then use binary search, or build a hash table for O(1) lookups. For graphs, you use breadth-first or depth-first search to find connected nodes or paths.
Searching is closely tied to the data structure: arrays support index access, linked lists require traversal, trees support recursive descent, and hash tables support direct key lookup. Picking the right structure up front often determines how fast your search will be.
Example
// Binary search — requires sorted array
function binarySearch(arr, target) {
let lo = 0, hi = arr.length - 1;
while (lo <= hi) {
const mid = Math.floor((lo + hi) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
const sorted = [1, 3, 5, 7, 9, 11, 13];
console.log(binarySearch(sorted, 7)); // 3 (index)
console.log(binarySearch(sorted, 4)); // -1 (not found)Binary search compares the middle element to the target and discards half the range each step. O(log n) time on sorted input.
Related terms
Related Resources
Related Lessons
- Algorithms
Learn searching algorithms.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.