![]() |
VOOZH | about |
Linear Search | Binary Search |
| In linear search input data need not to be in sorted. | In binary search input data need to be in sorted order. |
| It is also called sequential search. | It is also called half-interval search. |
| The time complexity of linear search O(n). | The time complexity of binary search O(log n). |
| Multidimensional array can be used. | Only single dimensional array is used. |
| Linear search performs equality comparisons. | Binary search performs ordering comparisons. |
| It is less complex. | It is more complex. |
| It is very slow process. | It is very fast process. |
Suppose we are searching a target element in an array. In linear search we begin with the first position of the array, and traverse the whole array in order to find the target element. If we find the target element we return the index of the element. Otherwise, we will move to the next position. If we arrive at the last position of an array and still can not find the target, we return -1. This is called the Linear search or Sequential search.
Working :
3
Time Complexity: O(n), where n is the size of the input array. The worst-case scenario is when the target element is not present in the array, and the function has to go through the entire array to figure that out.
Auxiliary Space: O(1), the function uses only a constant amount of extra space to store variables. The amount of extra space used does not depend on the size of the input array.
Binary Search is a more optimized form of searching algorithm. It cuts down the search space in halves achieving logarithmic time complexity on a sorted data. We take two extremes lower bound and upper bound and compare our target element with the middle element. In the process we discard one half where we are sure our target element can not be found and update our lower and upper bound accordingly.
Working :
3
Time Complexity: O(log n) - Binary search algorithm divides the input array in half at every step, reducing the search space by half, and hence has a time complexity of logarithmic order.
Auxiliary Space: O(1) - Binary search algorithm requires only constant space for storing the low, high, and mid indices, and does not require any additional data structures, so its auxiliary space complexity is O(1).