Search Algorithms Explained
Brute Force (Linear Search)
Linear search is the simplest search algorithm. It checks each element in the list sequentially until it finds the target value or reaches the end of the list.
Algorithm Steps:
- Start from the first element of the array
- Compare the current element with the target
- If they match, return the current index
- If they don't match, move to the next element
- Repeat steps 2-4 until the element is found or the end of the array is reached
- If the element is not found, return -1
Time Complexity:
| Case |
Time Complexity |
| Best Case |
O(1) - Target is the first element |
| Average Case |
O(n) |
| Worst Case |
O(n) - Target is the last element or not present |
Binary Search
Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item.
Algorithm Steps:
- Initialize two pointers:
left = 0 and right = array.length - 1
- While
left ≤ right:
- Calculate
mid = Math.floor((left + right) / 2)
- If the element at
mid is the target, return mid
- If the target is less than the element at
mid, set right = mid - 1
- If the target is greater than the element at
mid, set left = mid + 1
- If the element is not found, return -1
Time Complexity:
| Case |
Time Complexity |
| Best Case |
O(1) - Target is the middle element |
| Average Case |
O(log n) |
| Worst Case |
O(log n) - Target is at the beginning or end |
When to Use Each Algorithm
Use Linear Search when:
- The list is unsorted
- The list is small
- You need to find all occurrences of a value
Use Binary Search when:
- The list is sorted
- The list is large
- You need optimal search performance