Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Binary Search Algorithm

Uploaded by

nitinraj3009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Binary Search Algorithm

Uploaded by

nitinraj3009
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

56

DSA Course DSA Practice Divide and Conquer MCQs on Divide and Conquer Tutorial on Divide & Conquer Binary Search

Binary Search Algorithm – Iterative and Recursive


Implementation
Last Updated : 04 Sep, 2024

Binary Search Algorithm is a searching algorithm used in a sorted array by


repeatedly dividing the search interval in half. The idea of binary search is to use
the information that the array is sorted and reduce the time complexity to O(log N).

Binary Search Algorithm

Table of Content
What is Binary Search Algorithm?
Conditions to apply Binary Search Algorithm in a Data Structure
Binary Search Algorithm
How does Binary Search Algorithm work?
How to Implement Binary Search Algorithm?
Iterative Binary Search Algorithm:
Recursive Binary Search Algorithm:
Complexity Analysis of Binary Search Algorithm
Applications of Binary Search Algorithm
Advantages of Binary Search
Disadvantages of Binary Search
Frequently Asked Questions(FAQs) on Binary Search

What is Binary Search Algorithm?


Binary search is a search algorithm used to find the position of a target value within
a sorted array. It works by repeatedly dividing the search interval in half until the
target value is found or the interval is empty. The search interval is halved by
comparing the target element with the middle value of the search space.

Conditions to apply Binary Search Algorithm in a Data


Structure
To apply Binary Search algorithm:

The data structure must be sorted.


Access to any element of the data structure should take constant time.

Binary Search Algorithm


Below is the step-by-step algorithm for Binary Search:

Divide the search space into two halves by finding the middle index “mid”.
Compare the middle element of the search space with the key.
If the key is found at middle element, the process is terminated.
If the key is not found at middle element, choose which half will be used as the
next search space.
If the key is smaller than the middle element, then the left side is used
for next search.
If the key is larger than the middle element, then the right side is used
for next search.
This process is continued until the key is found or the total search space is
exhausted.

Binary Search Visualizer

Visualization of Binary Search


2 5 8 12 16 23 38 56 72 91

Enter a number to sear Start Search

Iterations: 0

How does Binary Search Algorithm work?


To understand the working of binary search, consider the following illustration:

Consider an array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91}, and the target = 23.
1/4

How to Implement Binary Search Algorithm?


The Binary Search Algorithm can be implemented in the following two ways

Iterative Binary Search Algorithm


Recursive Binary Search Algorithm

Given below are the pseudocodes for the approaches.

Iterative Binary Search Algorithm:

Here we use a while loop to continue the process of comparing the key and
splitting the search space in two halves.

C++ C Java Python C# JavaScript PHP

// C++ program to implement iterative Binary Search


#include <bits/stdc++.h>
using namespace std;

// An iterative binary search function.


int binarySearch(int arr[], int low, int high, int x)
{
while (low <= high) {
int mid = low + (high - low) / 2;

// Check if x is present at mid


if (arr[mid] == x)
return mid;

// If x greater, ignore left half


if (arr[mid] < x)
low = mid + 1;

// If x is smaller, ignore right half


else
high = mid - 1;
}

// If we reach here, then element was not present


return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, 0, n - 1, x);
if(result == -1) cout << "Element is not present in array";
else cout << "Element is present at index " << result;
return 0;
}

Output

Element is present at index 3

Time Complexity: O(log N)


Auxiliary Space: O(1)

Recursive Binary Search Algorithm:

Create a recursive function and compare the mid of the search space with the
key. And based on the result either return the index where the key is found or
call the recursive function for the next search space.

C++ C Java Python C# JavaScript PHP

1 #include <bits/stdc++.h>
2 using namespace std;
3
4 // A recursive binary search function. It returns
5 // location of x in given array arr[low..high] is present,
6 // otherwise -1
7 int binarySearch(int arr[], int low, int high, int x)
8 {
9 if (high >= low) {
10 int mid = low + (high - low) / 2;
11
12 // If the element is present at the middle
13 // itself
14 if (arr[mid] == x)
15 return mid;
16
17 // If element is smaller than mid, then
18 // it can only be present in left subarray
19 if (arr[mid] > x)
20 return binarySearch(arr, low, mid - 1, x);
21
22 // Else the element can only be present
23 // in right subarray
24 return binarySearch(arr, mid + 1, high, x);
25 }
26 return -1;
27 }
28
29 // Driver code
30 int main()
31 {
32 int arr[] = { 2, 3, 4, 10, 40 };
33 int query = 90;
34 int n = sizeof(arr) / sizeof(arr[0]);
35 int result = binarySearch(arr, 0, n - 1, query);
36 if (result == -1) cout << "Element is not present in
array";
37 else cout << "Element is present at index " << result;
38 return 0;
39 }

Output

Element is present at index 3

Complexity Analysis of Binary Search Algorithm


Time Complexity:
Best Case: O(1)
Average Case: O(log N)
Worst Case: O(log N)
Auxiliary Space: O(1), If the recursive call stack is considered then the auxiliary
space will be O(logN).

Applications of Binary Search Algorithm


Binary search can be used as a building block for more complex algorithms used in
machine learning, such as algorithms for training neural networks or finding the
optimal hyperparameters for a model.
It can be used for searching in computer graphics such as algorithms for ray
tracing or texture mapping.
It can be used for searching a database.

Advantages of Binary Search


Binary search is faster than linear search, especially for large arrays.
More efficient than other searching algorithms with a similar time complexity, such
as interpolation search or exponential search.
Binary search is well-suited for searching large datasets that are stored in
external memory, such as on a hard drive or in the cloud.

Disadvantages of Binary Search


The array should be sorted.
Binary search requires that the data structure being searched be stored in
contiguous memory locations.
Binary search requires that the elements of the array be comparable, meaning that
they must be able to be ordered.

Frequently Asked Questions(FAQs) on Binary Search

1. What is Binary Search?

Binary search is an efficient algorithm for finding a target value within a sorted
array. It works by repeatedly dividing the search interval in half.

2. How does Binary Search work?

Binary Search compares the target value to the middle element of the array. If
they are equal, the search is successful. If the target is less than the middle
element, the search continues in the lower half of the array. If the target is
greater, the search continues in the upper half. This process repeats until the
target is found or the search interval is empty.

3. What is the time complexity of Binary Search?

The time complexity of binary search is O(log2n), where n is the number of


elements in the array. This is because the size of the search interval is halved in
each step.

4. What are the prerequisites for Binary Search?

Binary search requires that the array is sorted in ascending or descending order.
If the array is not sorted, we cannot use Binary Search to search an element in
the array.

5. What happens if the array is not sorted for binary search?

You might also like