Linear Search vs Binary Search
Earlier we have seen linear search and binary search and how these work individually, In this article we will compare these two search algorithms. If you are new to these, please read the prerequisites below-
|SNo||Linear Search||Binary Search|
|1||Works with a sorted or unsorted array.||Works with sorted arrays only|
|2||Simple scan – iterates and compares one item at a time, either left to right or vice versa.||Removes half of the items after each comparison until the element is not found|
|3||For an array, iterate from the beginning to the end, and test each item in the array||After 1st iteration, N/2 items remain (N/21)|
After 2nd iteration, N/4 items remain (N/22)
After 3rd iteration, N/8 items remain (N/23)
|5||Time Complexity: O(N)||Time Complexity: Log2N|
Please see the code below and run on IDE for better understanding.
Linear Search.....Element 14 is found at index: 5 Binary Search.....Element 14 is found in array at index: 5 Linear Search.....Element 21 is not found in the array Binary Search.....Element 21 is not found in the array
Top Companies Interview Questions..-
If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.