Mastery Points
0
Searching Algorithms in dsa
Context & Logic
Searching is the process of finding a specific item in a collection of data. The two most common methods are Linear Search (for unsorted data) and Binary Search (for sorted data).
Example
// Binary Search: O(log n)
function binarySearch(arr, target) {
let low = 0, high = arr.length - 1;
while (low <= high) {
let mid = Math.floor((low + high) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}Step-by-Step Logic
1
Linear Search: Loop through each element until the target is found.
2
Binary Search: Repeatedly divide the search interval in half on a sorted array.
3
Check middle element: If it's the target, return index.
Complexity Metrics
Time Efficiency
Linear: O(n), Binary: O(log n)
Memory Footprint
O(1)