binary_search
binary_search
The objective of this lab is to implement and evaluate the performance of the Binary
Search algorithm in C++ for efficiently searching an element in a sorted array. The
aim is to understand the mechanics of the Binary Search technique, demonstrate
its superiority over linear search, and analyze its time complexity in the context of
large datasets. Additionally, this experiment seeks to explore the practical
application of the divide-and-conquer approach in solving search problems.
Theoretical Background:
Binary Search is a search algorithm that operates on a sorted array by repeatedly
dividing the search interval in half. If the value of the target is less than the item in
the middle of the array, the search continues in the lower half. Otherwise, it
continues in the upper half. This process repeats until the value is found or the
search interval is empty.
Key Points:
• Input: A sorted array and a target value.
• Time Complexity: O(log n) - Binary Search works in logarithmic time, making
it much faster than linear search for large arrays.
• Space Complexity: O(1) for the iterative approach.
• Working:
o The array is divided into two halves, and the middle element is
compared with the target.
o If the target matches the middle element, the index is returned.
o If the target is smaller than the middle element, the search continues
in the left half of the array.
o If the target is greater than the middle element, the search continues
in the right half.
Algorithm Pseudocode:
Input: A sorted array arr and a target value x
Output: The index of x in arr or -1 if x is not found
Algorithm Implementation:
#include <iostream>
using namespace std;
int arr[size];
cout << "Enter " << size << " sorted elements: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
int target;
cout << "Enter the element to search for: ";
cin >> target;
if (result != -1)
cout << "Element found at index: " << result << endl;
else
cout << "Element not found!" << endl;
return 0;
}
Output Screenshots:
Conclusion:
The Binary Search algorithm successfully locates the target value in a sorted array
with high efficiency, as demonstrated by the results of the experiment. Its time
complexity of 𝑂(log 𝑛) makes it a preferred choice for searching in large datasets
compared to linear search. The iterative implementation provides an optimal and
space-efficient approach. In this experiment, we successfully implemented and
tested the Binary Search algorithm in C++, and the results confirm its effectiveness
in solving the search problem efficiently.