logo
logo
Sign in

A Comprehensive Guide to Binary Search Algorithms

avatar
Anusha
A Comprehensive Guide to Binary Search Algorithms


 

[binary Search Algorithms - about & ways to use with examples]

 

The binary search algorithm is one of the most basic algorithms used in computing and mathematics. It is used to search a sorted set of data in an efficient manner. The efficiency of binary search makes it an essential tool for searching large data sets or arrays.

 

In this article, we will provide an introduction to binary search algorithms along with the different ways to use binary search algorithms and examples to demonstrate its uses.

 

An Overview of Binary Search Algorithms

 

Binary search is a class of search algorithms that are well-known for their effectiveness in finding particular elements within a sorted data collection. The fundamental principle of binary search is to divide the search space into two parts and constantly repeat the process until the desired element is found or is determined to be missing. Binary search is versatile and can be used in a variety of applications such as database systems, order structure maintenance, or numerical approximations. As a result, binary search is a fundamental concept in computational science and information retrieval.

 

Key Characteristics of Binary Search Algorithms

 

●    Sorted Data : In binary search algorithms, the input data must be sorted (usually in ascending or descending order). Sorting is necessary because the algorithm performs comparisons and makes decisions based on the relative order of the elements.

 

●    Divide and Conquer : Binary search works by dividing the search area in half and eliminating one of the halves. This reduces the number of elements that need to be considered, resulting in significantly shorter search times than linear search algorithms.

 

●    Efficiency : One of the features of binary search is that it is very fast. The time complexity of binary search is O(log N). In other words, N represents the number of elements of the input data. Because of this, binary search can handle large data sets efficiently. This is why binary search is preferred for tasks such as searching in databases or keeping ordered data structures.

 

Ways to Use Binary Search

 

Some of the key and common variations of binary search algorithms are highlighted here, along with examples to help understand their uses better.

 

1. Basic Binary Search :

 

The basic binary search is a common binary search algorithm that looks for a particular element in a sorted collection or list. It checks if the element is in the collection and if it is, it returns its index.

 

Algorithm :

1.  Initialize two pointers, ‘left’ and ‘right’ , to the start and end of the array, respectively.

2.  While ‘left’ is less than or equal to ‘right’ :

a.  Calculate the middle index as ‘mid = ( left + right ) // 2’

b.  If the middle element is equal to the target value, return its index.

c.   If the middle element is less than target value, update ‘left = mid + 1’

d.  If the middle element is greater than the target value, update ‘right = mid - 1’

3. If the loop exits without finding the target value, return -1 to indicate that it does not exist in the array.

 

Example :

 

‘’ python :

 

def binary_search(arr, target):

   left, right = 0, len(arr) - 1

   while left <= right:

       mid = (left + right) // 2

       if arr[mid] == target:

           return mid

       elif arr[mid] < target:

           left = mid + 1

       else:

           right = mid - 1

   return -1

 

 

2.   Binary Search Variations

Binary search isn’t just about finding one thing - it can be used to solve a bunch of different problems.

Here’s a list of some of the most common variations :

 

a.  Lower Bound Binary Search :

Using a lower bound binary search, you can find the lowest point at which you can put a given value in a sorted field without breaking the order. This is also known as a lower bound or first occurrence binary search.

 

Algorithm :

 

1. Initialize two pointers, `left` and `right`, to the start and end of the array, respectively.

2. While `left` is less than `right`:

  a. Calculate the middle index as `mid = (left + right) // 2`.

  b. If the middle element is less than the target value, update `left = mid + 1`.

  c. Otherwise, update `right = mid`.

3. After the loop, `left` will be the index of the first occurrence (lower bound) of the target value.

 

Example :

 

```python

def lower_bound_binary_search(arr, target):

   left, right = 0, len(arr)

   while left < right:

       mid = (left + right) // 2

       if arr[mid] < target:

           left = mid + 1

       else:

           right = mid

   return left

```

 

 

 

b.  Upper Bound Binary Search :

 

Higher bound binary search works in the same way as lower bound binary searching, but it looks for the lowest point at which you can put a value in a sorted field without going over the specified value. It is also known as upper bound or last occurrence binary search.

 

Algorithm :

 

1. Initialize two pointers, `left` and `right`, to the start and end of the array, respectively.

2. While `left` is less than `right`:

  a. Calculate the middle index as `mid = (left + right) // 2`.

  b. If the middle element is less than or equal to the target value, update `left = mid + 1`.

  c. Otherwise, update `right = mid`.

3. After the loop, `left` will be the index of the last occurrence (upper bound) of the target value.

 

Example :

 

```python

def upper_bound_binary_search(arr, target):

   left, right = 0, len(arr)

   while left < right:

       mid = (left + right) // 2

       if arr[mid] <= target:

           left = mid + 1

       else:

           right = mid

   return left

```

 

 

c.  Count of Occurences Binary Search :

 

This variant of binary search calculates the number of occurrences of a given target value in a pre-arranged array. It is a combination of lower bound and upper bound binary searches.

 

Algorithm :

 

1. Find the lower bound of the target value using lower bound binary search.

2. Find the upper bound of the target value using upper bound binary search.

3. The count of occurrences is given by `upper_bound - lower_bound`.

 

Example :

 

```python

def count_occurrences(arr, target):

   lower = lower_bound_binary_search(arr, target)

   upper = upper_bound_binary_search(arr, target)

   return upper - lower

```

 

3. Binary Search in 2D Arrays

 

Binary search is also applicable to two-dimensional (matrix) arrays. In the following example, a target value is being sought in a matrix in which each row and column are sorted :

 

Algorithm :

 

1. Initialize `row` to 0 (the top row) and `col` to the number of columns minus 1 (the rightmost column).

2. While `row` is within bounds (less than the number of rows) and `col` is within bounds (greater than or equal to 0):

  a. If the element at `matrix[row][col]` is equal to the target value, return `True`.

  b. If the element is less than the target value, increment `row` to move down in the matrix.

  c. If the element is greater than the target value, decrement `col` to move left in the matrix.

3. If the loop exits without finding the target value, return `False`.

 

Example :

 

```python

def search_matrix(matrix, target):

   if not matrix:

       return False

   

   rows, cols = len(matrix), len(matrix[0])

   row, col = 0, cols - 1

   

   while row < rows and col >= 0:

       if matrix[row][col] == target

 

 

Implementation Approaches

 

Binary search algorithms can be implemented using two primary approaches - iterative and recursive .

 

With the iterative approach you use a loop structure to divide the search space and update pointers or indices until you find the target element or until the search space is full. This approach is usually the go-to because it is easy to use and does not take up a lot of memory.

 

Recursive approach on the other hand, is when you define a function and tell it to call itself with different parameters. This breaks the problem down into smaller problems until you get to the base case (like finding the target or determining it’s not there). Recursive implementations are usually more elegant and straightforward, but they can take up more memory because of the call stack, so they’re not great for large datasets. It all depends on the problem, the language, and your programming preferences.

 

Applications of Binary Search Algorithms :

 

Binary search algorithms are utilized extensively in a variety of industries due to their effectiveness in sorting data. Here are some f the common uses of binary search algorithms :

 

●    Database Search : Binary search is used a lot in databases to quickly find the right records based on the indexed column. It helps you get the data you need quickly, especially if you have a lot of data, by narrowing down the search area to the right records.

 

●    Information Retrieval : Binary search is used in information retrieval systems such as search engines (SEOs) and document databases (DBs) to find related documents, web pages or data based on users’ queries or keywords. Binary search can quickly find and rank results from large collections of information.

 

●    Sorting Algorithms : Binary search plays a big part in a bunch of sorting algorithms, like merge sort, quicksort, etc. It's used to split up the data while sorting, which makes it faster, especially if you're dealing with a lot of data.

 

●    Data Structures : Binary search is essential for keeping things in order, like binary search trees. BTRs use binary search to quickly and easily add, remove, and get data in a sorted way, which makes them useful for things like making dictionaries and keeping collections in order.

 

●    Auto-Completion and Spell Checking : Binary search can be used in user interfaces and in word processing software to suggest auto-completion as you type. Binary search can quickly identify and suggest words or phrases from the sorted dictionary or vocabulary. This improves the user experience and improves spelling and grammar checking.

 

All of these applications demonstrate the versatility and effectiveness of binary search algorithms when used to solve problems related to data collection, sorting, or information processing in a variety of domains.

 

Conclusion,

All in all, binary search is a powerful tool for finding sorted collections efficiently. Whether you want to find a particular element, find the insertion point, count occurrences, or search in 2D arrays, binary search offers a fast and efficient solution. Its divide-and-conquer approach, in combination with the sorted data requirement, reduces the search space significantly with each iteration. This makes binary search an indispensable tool for solving a wide variety of problems in the field of computer science and elsewhere. While binary search is very powerful, it is important to remember that your data must be sorted before using this algorithm.

 

Choosing the right binary search variant for your particular problem can result in elegant and effective solutions. By mastering binary search and variations, you will be better prepared to solve complex search problems and optimize your algorithms to perform at their best. 

collect
0
avatar
Anusha
guide
Zupyak is the world’s largest content marketing community, with over 400 000 members and 3 million articles. Explore and get your content discovered.
Read more