Linear Search vs Binary Search

Linear Search vs Binary Search

Linear Search is the most basic type of searching algorithm. A Linear Search sequentially moves through your collection (or data structure) looking for a matching value. In other words, it looks down a list, one item at a time, without jumping. Think of it as a way of finding your way in a phonebook

Binary search is an efficient algorithm for finding an item from a sorted list of items. It works by repeatedly dividing in half the portion of the list that could contain the item, until you’ve narrowed down the possible locations to just one.

A linear search scans one item at a time, without jumping to any item .

  1. The worst case complexity is  O(n), sometimes known an O(n) search
  2. Time taken to search elements keep increasing as the number of elements are increased.

A binary search however, cut down your search to half as soon as you find middle of a sorted list.

  1. The middle element is looked to check if it is greater than or less than the value to be searched.
  2. Accordingly, search is done to either half of the given list

Important Differences

  • Input data needs to be sorted in Binary Search and not in Linear Search
  • Linear search does the sequential access whereas Binary search access data randomly.
  • Time complexity of linear search -O(n) , Binary search has time complexity O(log n).
  •  Linear search performs equality comparisons and Binary search performs ordering comparisons

Let us look at an example to compare the two:

Linear Search to find the element “J” in a given sorted list from A-X

Linear search example
Linear search example

 

 

 

 

 

 

 

Binary Search to find the element “J” in a given sorted list from A-X

 

Binary search example
Binary search example