You are on page 1of 1

Q.

when we use binary search and linear search


Binary search and linear search are two different algorithms used for searching elements in a
data structure, typically an array. The choice between them depends on the characteristics of
the data and the requirements of the specific situation.
1. Linear Search:
- Use when:
- The list is unsorted.
- You have no prior knowledge of the order of elements.
- The list is small, as linear search can be inefficient for large lists.
- You need a simple algorithm with minimal overhead.
- How it works: Linear search goes through each element of the list sequentially until it
finds the target element or reaches the end of the list.
2. Binary Search:
- Use when:
- The list is sorted. Binary search requires the list to be in sorted order.
- You are dealing with large datasets, as binary search is more efficient than linear search
for large datasets.
- You need a fast search algorithm and the cost of sorting the list is not a concern or the list
is already sorted.
- How it works: Binary search repeatedly divides the sorted list into halves, discarding the
half that is certain not to contain the target element, until the target is found or the search
space is empty.

In summary, use linear search for small or unsorted lists where simplicity and minimal
overhead are important, and use binary search for large, sorted lists where efficiency is a
priority.

You might also like