0% found this document useful (0 votes)
19 views9 pages

Binary Search

Uploaded by

lonesome.rar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Binary Search

Uploaded by

lonesome.rar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

1/2/25, 12:17 PM Binary Search

AfterAcademy

Admin AfterAcademy
18 Jul 2020

Binary Search

Difficulty: Easy

Understanding The Problem


Problem Description

Given a sorted integer array arr[] of n elements and a target value k ,


write a program to search k in arr[] .

https://afteracademy.com/blog/binary-search/ 1/9
1/2/25, 12:17 PM Binary Search

Problem Note

If k exists, then return its index, otherwise, return -1.

You may assume that all elements in arr[] are unique.

Example 1

Input: arr[] = [1, 5, 6, 7, 9, 10, 50], k= 9


Output: 4
Explanation: 9 exists in arr[] and its index is 4.

Example 2

Input: arr[] = [1, 5, 6, 7, 9, 10, 50], target = 20


Output: -1
Explanation: 20 does not exist in arr[] so return -1.

You may try to solve the problem here.

Solution
We need to return the position of an element that needs to be searched in a
sorted array.

The question clearly needs us to perform Binary Search. This searching


technique works on the sorted arrays.

The binary search begins by comparing an element in the middle of the


array with the target value. If the target value matches the element, its
position in the array is returned. If the target value is less than the element,
the search continues in the lower half of the array. If the target value is
greater than the element, the search continues in the upper half of the
array.

https://afteracademy.com/blog/binary-search/ 2/9
1/2/25, 12:17 PM Binary Search

By doing this, the algorithm eliminates the half in which the target value
cannot lie in each iteration.

This searching technique is far more efficient than the linear search. Look
at the example below.

Solution Steps

1. Set L to 0 and R to n-1.

2. If L > R, the search terminates as unsuccessful.

3. Set m (the position of the middle element) to the floor of (l + r) / 2

4. If A[m] < T, set L to m+1 and go to step 2.

5. If A[m] > T, set R to m-1 and go to step 2.

6. If A[m]=T, the search is done and return m.

Pseudo Code

https://afteracademy.com/blog/binary-search/ 3/9
1/2/25, 12:17 PM Binary Search

Recursive Binary Search

int binarySearch(int arr[], int l, int r, int T) {


if (l <= r) {
int mid = l + (r - l) / 2
if (arr[mid] == T)
return mid
if (arr[mid] > T)
return binarySearch(arr, l, mid - 1, T)
return binarySearch(arr, mid + 1, r, T)
}
return -1
}

Complexity Analysis

Time Complexity: O(log n)

Space Complexity: O(log n), considering recursion stack space

Iterative Binary Search

int binarySearch(int arr[], int l, int r, int T)


{
while (l <= r) {
int m = l + (r - l) / 2
if (arr[m] == T)
return m
if (arr[m] < T)
l = m + 1
else
r = m - 1
}
return -1
}

Complexity Analysis

Time Complexity: O(log n)


https://afteracademy.com/blog/binary-search/ 4/9
1/2/25, 12:17 PM Binary Search

Space Complexity: O(1)

Here’s a table showing the base-2 logarithms of various values of n :

Critical Ideas To Think

Can we replace while(l≤r) with while(l<r) ? If not, then why?

How did we make sure than if the target < arr[m] , then the target
will exist only on the left of mid?

Perform recursive binary search over some custom example?

The 2014 “Catalogue of Life” contains about 1580000 names of species.


If these names were sorted in an array, in the worst case, how many

https://afteracademy.com/blog/binary-search/ 5/9
1/2/25, 12:17 PM Binary Search

comparisons would it take for the binary search to find the name of a
particular species in the array?

Can you list the places where is Binary search algorithm is used?

Suggested Problems To Solve


Write the code for pow(x, n) function

Write the code for sqrt(x) function

Search in a 2D Matrix

Find Minimum in Rotated Sorted Array

Find Peak Element

Dungeon Game

Minimum Size Subarray Sum

If you have any more approaches or you find an error/bug in the above
solutions, please comment down below.

Happy Coding!

Enjoy Algorithms!

Recommended for You

https://afteracademy.com/blog/binary-search/ 6/9
1/2/25, 12:17 PM Binary Search

Average of Levels in Find The Height Of a


Binary Tree Binary Tree
Given a binary tree, write a program to Given a binary tree, write a program to find
return the average value of the nodes on the maximum depth of the binary tree. The
each level in the form of an array. The range maximum depth is the number of nodes
of the node's value is in the range of 32-bit along the longest path from the root node to
signed integer. the leaf node. A leaf is a node with no child
nodes.

Admin AfterAcademy Admin AfterAcademy


5 Nov 2020 3 Nov 2020

Merge Two BST Search in a 2-D Matrix


Given two binary search trees with root You are given a matrix arr of m x n size.
nodes as tree1 and tree2 of size n and m, Write a program to searches for a value k in
write a program to return an array of arr. This arr has the following properties: -
integers that contains all the elements of Integers in each row are sorted from left to
tree1 and tree2 in non-decreasing order. The right. - The first value of each row is greater
expected time complexity is O(m+n). than the last value of previous row. This is a
basic optimization problem that will clear
the concept of searching.

Admin AfterAcademy Admin AfterAcademy


1 Sep 2020 18 Jul 2020

https://afteracademy.com/blog/binary-search/ 7/9
1/2/25, 12:17 PM Binary Search

Maximal Square Recover Binary Search Tree-


You are given a 2D binary matrix arr[][] filled Interview Problem
with 0's and 1's. The array contains a square Given a Binary Search Tree such that two of
of 1's. So, you need to find that square and the nodes of this tree have been swapped
return its area. The problem is a great by mistake. You need to write a program
example for practicing dynamic that will recover this BST while also
programming for technical interviews. maintaining its original structure

Admin AfterAcademy Admin AfterAcademy


18 Jul 2020 16 Jun 2020

Connect With Your Mentors

https://afteracademy.com/blog/binary-search/ 8/9
1/2/25, 12:17 PM Binary Search

Janishar Ali Amit Shekhar


Founder | IIT-BHU | 10 Yrs Exp. Founder | IIT-BHU | 10 Yrs Exp.

Copyright 2022, MindOrks Nextgen Private Limited

https://afteracademy.com/blog/binary-search/ 9/9

You might also like