Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis (2024)

/ #Algorithms
Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis (1)
Ashutosh Krishna
Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis (2)

Search algorithms are a fundamental computer science concept that you should understand as a developer. They work by using a step-by-step method to locate specific data among a collection of data.

In this article, we'll learn how search algorithms work by looking at their implementations in Java and Python.

What is a Search Algorithm?

According to Wikipedia, a search algorithm is:

Any algorithm which solves the search problem, namely, to retrieve information stored within some data structure, or calculated in the search space of a problem domain, either with discrete or continuous values.

Search algorithms are designed to check or retrieve an element from any data structure where that element is being stored. They search for a target (key) in the search space.

Types of Search Algorithms

In this post, we are going to discuss two important types of search algorithms:

  1. Linear or Sequential Search
  2. Binary Search

Let's discuss these two in detail with examples, code implementations, and time complexity analysis.

Linear or Sequential Search

This algorithm works by sequentially iterating through the whole array or list from one end until the target element is found. If the element is found, it returns its index, else -1.

Now let's look at an example and try to understand how it works:

arr = [2, 12, 15, 11, 7, 19, 45]

Suppose the target element we want to search is 7.

Approach for Linear or Sequential Search

  • Start with index 0 and compare each element with the target
  • If the target is found to be equal to the element, return its index
  • If the target is not found, return -1

Code Implementation

Let's now look at how we'd implement this type of search algorithm in a couple different programming languages.

Linear or Sequential Search in Java

package algorithms.searching;public class LinearSearch { public static void main(String[] args) { int[] nums = {2, 12, 15, 11, 7, 19, 45}; int target = 7; System.out.println(search(nums, target)); } static int search(int[] nums, int target) { for (int index = 0; index < nums.length; index++) { if (nums[index] == target) { return index; } } return -1; }}

Linear or Sequential Search in Python

def search(nums, target): for i in range(len(nums)): if nums[i] == target: return i return -1if __name__ == '__main__': nums = [2, 12, 15, 11, 7, 19, 45] target = 7 print(search(nums, target))

Time Complexity Analysis

The Best Case occurs when the target element is the first element of the array. The number of comparisons, in this case, is 1. So, the time complexity is O(1).

The Average Case: On average, the target element will be somewhere in the middle of the array. The number of comparisons, in this case, will be N/2. So, the time complexity will be O(N) (the constant being ignored).

The Worst Case occurs when the target element is the last element in the array or not in the array. In this case, we have to traverse the entire array, and so the number of comparisons will be N. So, the time complexity will be O(N).

Binary Search

This type of searching algorithm is used to find the position of a specific value contained in a sorted array. The binary search algorithm works on the principle of divide and conquer and it is considered the best searching algorithm because it's faster to run.

Now let's take a sorted array as an example and try to understand how it works:

arr = [2, 12, 15, 17, 27, 29, 45]

Suppose the target element to be searched is 17.

Approach for Binary Search

  • Compare the target element with the middle element of the array.
  • If the target element is greater than the middle element, then the search continues in the right half.
  • Else if the target element is less than the middle value, the search continues in the left half.
  • This process is repeated until the middle element is equal to the target element, or the target element is not in the array
  • If the target element is found, its index is returned, else -1 is returned.

Code Implementation

Binary Search in Java

package algorithms.searching;public class BinarySearch { public static void main(String[] args) { int[] nums = {2, 12, 15, 17, 27, 29, 45}; int target = 17; System.out.println(search(nums, target)); } static int search(int[] nums, int target) { int start = 0; int end = nums.length - 1; while (start <= end) { int mid = start + (end - start) / 2; if (nums[mid] > target) end = mid - 1; else if (nums[mid] < target) start = mid + 1; else return mid; } return -1; }}

Binary Search in Python

def search(nums, target): start = 0 end = len(nums)-1 while start <= end: mid = start + (end-start)//2 if nums[mid] > target: end = mid-1 elif nums[mid] < target: start = mid+1 else: return mid return -1if __name__ == '__main__': nums = [2, 12, 15, 17, 27, 29, 45] target = 17 print(search(nums, target))

Time Complexity Analysis

The Best Case occurs when the target element is the middle element of the array. The number of comparisons, in this case, is 1. So, the time complexity is O(1).

The Average Case: On average, the target element will be somewhere in the array. So, the time complexity will be O(logN).

The Worst Case occurs when the target element is not in the list or it is away from the middle element. So, the time complexity will be O(logN).

How to Calculate Time Complexity:

Let's say the iteration in Binary Search terminates after k iterations.

At each iteration, the array is divided by half. So let’s say the length of array at any iteration is N.

At Iteration 1,

Length of array = N

At Iteration 2,

Length of array = N/2

At Iteration 3,

Length of array = (N/2)/2 = N/2^2

At Iteration k,

Length of array = N/2^k

Also, we know that after k divisions, the length of the array becomes 1: Length of array = N⁄2k = 1=> N = 2k

If we apply a log function on both sides: log2 (N) = log2 (2k)=> log2 (N) = k log2 (2)

As (loga (a) = 1)
Therefore,=> k = log2 (N)

So now we can see why the time complexity of Binary Search is log2 (N).

You can also visualize the above two algorithms using the simple tool built by Dipesh Patil - Algorithms Visualizer.

Order-agnostic Binary Search

Suppose, we have to find a target element in a sorted array. We know that the array is sorted, but we don’t know if it’s sorted in ascending or descending order.

Approach for Order-agnostic Binary Search

The implementation is similar to binary search except that we need to identify whether the array is sorted in ascending order or descending order. This then lets us make the decision about whether to continue the search in the left half of the array or the right half of the array.

  • We first compare the target with the middle element
  • If the array is sorted in ascending order and the target is less than the middle element OR the array is sorted in descending order and the target is greater than the middle element, then we continue the search in the lower half of the array by setting end=mid-1.
  • Otherwise, we perform the search in the upper half of the array by setting start=mid+1

The only thing we need to do is to figure out whether the array is sorted in ascending order or descending order. We can easily find this by comparing the first and last elements of the array.

if arr[0] < arr[arr.length-1] array is sorted in ascending order else array is sorted in descending order

Code Implementation

Order-agnostic Binary Search in Java

package algorithms.searching;public class OrderAgnosticBinarySearch { public static void main(String[] args) { int[] nums1 = {-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99}; int[] nums2 = {99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1}; int target = -1; System.out.println(search(nums1, target)); System.out.println(search(nums2, target)); } static int search(int[] arr, int target) { int start = 0; int end = arr.length - 1; boolean isAscending = arr[start] < arr[end]; while (start <= end) { int mid = start + (end - start) / 2; if (target == arr[mid]) return mid; if (isAscending) { if (target < arr[mid]) { end = mid - 1; } else { start = mid + 1; } } else { if (target < arr[mid]) { start = mid + 1; } else { end = mid - 1; } } } return -1; }}

Order-agnostic Binary Search in Python

def search(nums, target): start = 0 end = len(nums)-1 is_ascending = nums[start] < nums[end] while start <= end: mid = start + (end-start)//2 if target == nums[mid]: return mid if is_ascending: if target < nums[mid]: end = mid-1 else: start = mid+1 else: if target < nums[mid]: start = mid+1 else: end = mid-1 return -1if __name__ == '__main__': nums1 = [-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99] nums2 = [99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1] target = -1 print(search(nums1, target)) print(search(nums2, target))

Time Complexity Analysis

There will be no change in the time complexity, so it will be the same as Binary Search.

In this article, we discussed two of the most important search algorithms along with their code implementations in Python and Java. We also looked at their time complexity analysis.

Thanks for reading!

Subscribe to my newsletter

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

ADVERTIsem*nT

Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis (3)
Ashutosh Krishna

Application Developer at Thoughtworks India

If you read this far, thank the author to show them you care.

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

ADVERTIsem*nT

Search Algorithms – Linear Search and Binary Search Code Implementation and Complexity Analysis (2024)

FAQs

What is the complexity of binary search and linear search? ›

Linear Search has a time complexity of O(n), while Binary Search has a time complexity of O(log n). Binary Search requires sorted data, whereas Linear Search does not. Binary Search is more complex to implement compared to Linear Search.

How do you implement linear search and binary search? ›

We will traverse the array linearly in linear search and compare each array value with the key linearly, sequential. In binary search, we will apply the divide and conquer approach; first, we will find the mid element and then divide the array into two parts.

What are the three search algorithms? ›

Search algorithms can be classified based on their mechanism of searching into three types of algorithms: linear, binary, and hashing.

What is the difference between linear and binary search algorithms? ›

The major difference between linear search and binary search in terms of working is that the linear search compares all the elements with the key that needs to be searched. But binary search can reduce the size of the array which should be searched, and the binary search compares the key with the mid element.

Which is faster linear or binary search? ›

Based on their time complexities, binary search is significantly faster than linear search for large data sets. As the number of elements increases, the logarithmic growth of binary search outperforms the linear growth of linear search.

Which searching technique is best? ›

Binary search is a highly efficient search method that works best with sorted data structures. It employs the "divide and conquer" approach, repeatedly dividing the search space in half until the desired element is located. This results in significantly faster searching for large datasets.

What is the fastest search algorithm? ›

Binary Search is the fastest searching algorithm for sorted data. It takes O(log2N) time to search any element in the sorted search space. In this article, we will discuss about how Binary Search works, it time complexity, comparison with other search algorithms, etc.

What searching algorithm is used by Google? ›

PageRank (PR) is an algorithm used by Google Search to rank web pages in their search engine results. It is named after both the term "web page" and co-founder Larry Page. PageRank is a way of measuring the importance of website pages.

What is the simplest search algorithm? ›

Linear search is the simplest search algorithm. It works by checking each element of the data one by one until it finds the target or reaches the end. Linear search is easy to implement and does not require any prior sorting or ordering of the data.

What is the purpose of a search algorithm? ›

Search algorithms are designed to check or retrieve an element from any data structure where that element is being stored. They search for a target (key) in the search space.

What is the complexity of a binary search? ›

Time complexity of Binary Search is O(log n), where n is the number of elements in the array. It divides the array in half at each step. Space complexity is O(1) as it uses a constant amount of extra space.

What is the complexity of linear search? ›

Linear Search Complexity

Linear search runs in linear time and makes a maximum of n comparisons, where n is the length of the list. Hence, the computational complexity for linear search is O(N).

Which is better search algorithm than binary? ›

Interpolation search works better than Binary Search for a Sorted and Uniformly Distributed array. Binary Search goes to the middle element to check irrespective of search-key. On the other hand, Interpolation Search may go to different locations according to search-key.

What are the complexities of binary search? ›

The time complexity of binary search is, therefore, O(logn). This is much more efficient than the linear time O(n), especially for large values of n. For example, if the array has 1000 elements.

Which is greater, O'n or O logn? ›

therefore, O(logn) is tighter than O(n) and is also better in terms of algorithms analysis. But all the algorithms that are O(logn) are also O(n), but not backwards... O(log n) is better.

Is linear search always slower than a binary search? ›

Binary search is almost always much faster. For example, imagine searching a million items, where the things we're looking for are more-or-less randomly distributed. Then linear search will take on average 500,000 checks, and at worst 1,000,000 checks.

Why is space complexity of linear search o(1)? ›

Let us assume that your model of computations consider the space required other than input then linear search will take O(1) space as you only need to store the (current) index of the input array. There are n elements in the array so O(log n) bits are needed for indexing the array.

Top Articles
Latest Posts
Article information

Author: Lilliana Bartoletti

Last Updated:

Views: 5525

Rating: 4.2 / 5 (73 voted)

Reviews: 88% of readers found this page helpful

Author information

Name: Lilliana Bartoletti

Birthday: 1999-11-18

Address: 58866 Tricia Spurs, North Melvinberg, HI 91346-3774

Phone: +50616620367928

Job: Real-Estate Liaison

Hobby: Graffiti, Astronomy, Handball, Magic, Origami, Fashion, Foreign language learning

Introduction: My name is Lilliana Bartoletti, I am a adventurous, pleasant, shiny, beautiful, handsome, zealous, tasty person who loves writing and wants to share my knowledge and understanding with you.