Lecture 1.2.5. Binary Search
Lecture 1.2.5. Binary Search
BCA/BSC CS
DATA STRUCTURES
(22CAT-211/22SCT-211/22CAT231)
1
Content
2
Chapter 2 (Unit I)
• Lecture1.2.5. Binary search
14/06/2024
Searching operation in array
4
• Binary search looks for a particular item by comparing the middle most item
of the collection. If a match occurs, then the index of item is returned. If the
middle item is greater than the item, then the item is searched in the sub-
array to the left of the middle item.
• Otherwise, the item is searched for in the sub-array to the right of the middle
item. This process continues on the sub-array as well until the size of the
subarray reduces to zero.
[1]
Binary Search Algorithm
Procedure binary_search
A ← sorted array
n ← size of array
x ← value to be searched
Set lowerBound = 1
Set upperBound = n
while x not found
if upperBound < lowerBound
EXIT: x does not exists
7
[4]
Implementation of linear search
9
• #include <bits/stdc++.h>
• using namespace std;
• // A recursive binary search function. It returns location of x in given array arr[l..r] is present, otherwise -1
• int binarySearch(int arr[], int l, int r, int x)
• {
• if (r >= l) {
• int mid = l + (r - l) / 2;
• // If the element is present at the middle itself
• if (arr[mid] == x)
• return mid;
• // If element is smaller than mid, then it can only be present in left subarray
•
Code (contd..)
• if (arr[mid] > x)
10
• return binarySearch(arr, l, mid - 1, x);
•
• // Else the element can only be present
• // in right subarray
• return binarySearch(arr, mid + 1, r, x);
• }
•
• // We reach here when element is not
• // present in array
• return -1;
• }
•
Code (contd..)
11
• 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);
• (result == -1)
• ? cout << "Element is not present in array"
• : cout << "Element is present at index " << result;
• return 0;
Complexity of binary search
12
[2]
Frequently asked questions
14
14/06/2024
REFERENCES
15
[1] https://www.atnyla.com/tutorial/operations-on-array/3/521
[2] https://www.tutorialspoint.com/data_structures_algorithms/binary_search_algorithm.htm
[3] https://www.thedshandbook.com/searching-in-arrays/
[4] https://medium.com/techie-delight/binary-search-practice-problems-4c856cd9f26c
14/06/2024
THANK YOU