DEV Community

shopeyin
shopeyin

Posted on

Understanding Linear Search and Binary Search in Programming

Searching refers to iterating over the data structure's elements to retrieve some data. When searching in an array, there are two main techniques depending on whether the array is sorted.
With regards to Linear and Binary searching, Linear searches are especially flexible because they can be used with both sorted and unsorted data while Binary searches are specifically used with sorted data.

Linear Search
A linear search works by going through each element of the array one index after another sequentially. The following code example is an implementation of a linear search that iterates through the entire array of numbers to find out whether an item exists within the array.

Alt Text

The time complexity of the linear Search algorithm is O(n) because in the worst-case scenario it will search through all the elements before return false

Binary Search

Binary Search is a searching algorithm that works on sorted array. Unlike the linear search algorithm in which every element of the array is checked, binary searches can check the middle value to see whether the desired value is greater or smaller than it. If the desired value is smaller, this algorithm can search through the smaller parts, or it can search through the bigger parts if the desired value is bigger.

Alt Text

The binary Search algorithm is fast but can be done only if the array is sorted. It checks the middle element if that is the element that is being searched for. If the search
element is bigger than the middle element, the lower bound is set to the middle element plus one. If the search element is less than the middle element, the higher bound is set to
the middle element minus one.

Top comments (0)