Introduction
In this blog, I am going to discuss two of the most commonly-used searching algorithms in the programming world -
- Linear Search
- Binary Search
I will be explaining the algorithms with the help of an example and will provide a C# code to execute that.
Linear Search
This algorithm will perform a sequential search of item in the given array. Every element is checked from start to end and if a match is found, the index of matched element will be returned; otherwise, -1 will be returned.
- procedure LinearSearch(array, value)
- foreach item in array
- if item == value
- return the item's index
- end if
- end foreach
- return -1
- end procedure
Let us understand this with the help of an example.
Consider the array below.
If we want to determine the position of number 1 in this array, we have to traverse every element from start to end; i.e from index=0 to index = 7 and compare it with 1. We will return the position of element which matches with 1, which is 6 (index+1). Hence, the element 1 is found at position 6 in input array.
Time Complexity
Since all the array elements are compared only once with the input element, hence the time complexity of the linear search is O(N).Binary Search
Binary search is an efficient and commonly used searching algorithm.This algorithm works only on sorted sets of elements. So if the given array is not sorted then we need to sort it before applying Binary search.
This algorithm searches 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.if found return the index of matched element , else return -1.

Dmitry MironovPosted Jan 30, 2021, 10:33 AM
Thanks :-)
Mayur DeorePosted Sep 5, 2017, 1:25 PM
Nice article.There is small mistake in BInarySearch Pseudocode. You have mentioned Set lowerBound = 1 Instead of Set lowerBound = 0