Linear and Binary Search
Linear and Binary Search
When it comes to search arrays there are two approaches exist 1) un-sorted array search
using Sequential/linear search.
If given a sorted array arr[] of n elements, write a function to search a given element x in arr[].
A simple approach is to do a linear search. The time complexity of the above algorithm is O(n). Another
approach to perform the same task is using Binary Search.
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an
interval covering the whole array. If the value of the search key is less than the item in the middle of the
interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check
until the value is found or the interval is empty. Example :
Algorithm:
Here low contains the starting index of array and high contains the last index and mid contain the middle index of
array
Linear Search:
Linear search is one of the simplest approach when it comes to searching in arrays
Algorithm:
1. Start from the leftmost element of arr[] and one by one compare x with each element of arr[]
Linear
Binary