Linear vs. binary search (2024)

Table of Contents
Linear search Binary search

Linear and binary searches are algorithms used to find a specific element from a linear data set (such as an array, linked list, etc.) The algorithms only differ in the methodology employed to find the desired element. Before understanding the differences, let us look at each search individually.

Linear search

A linear search scans each element of the array sequentially until the required element is identified. As a result, the worst time complexity is of the order O(n)O(n)O(n) since the time required to search an element is proportional to the number of the elements.

/// Linear Search PsedocodeWhile (element_found = False and counter < Length(List)) If (list[counter] = element_required) element_found = true Display (list[counter]) Else counter = counter + 1 if (counter = Length(list) + 1) Display ('Element not found')

Binary search

A binary search finds the required element in an array via middle element value comparison; hence, cutting the array length to be searched in each scan cycle by half. This leads to faster computation and reduces the worst time complexity to O(logn)O(log \space n)O(logn). However, the prerequisite for a binary search to work is that the array must be sorted.

/// Binary Search Pseudocodeleft = 0right = length(list) - 1while (left <= right) counter = floor((left + right) / 2) if (list[counter] < element_ required) left = counter + 1 if (list[counter] > element_required) right = counter - 1 else Display(list[counter])
Linear vs. binary search (2024)
Top Articles
Latest Posts
Article information

Author: Fredrick Kertzmann

Last Updated:

Views: 5736

Rating: 4.6 / 5 (46 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Fredrick Kertzmann

Birthday: 2000-04-29

Address: Apt. 203 613 Huels Gateway, Ralphtown, LA 40204

Phone: +2135150832870

Job: Regional Design Producer

Hobby: Nordic skating, Lacemaking, Mountain biking, Rowing, Gardening, Water sports, role-playing games

Introduction: My name is Fredrick Kertzmann, I am a gleaming, encouraging, inexpensive, thankful, tender, quaint, precious person who loves writing and wants to share my knowledge and understanding with you.