Binary Search C++ Report
Binary Search C++ Report
Page Numbers:
[Ensure every page is numbered]
Objectives
To implement the Binary Search algorithm in C++ language.
To understand how Binary Search operates on a sorted array.
To evaluate the time complexity of Binary Search in a sorted list.
Lab Materials
C++ programming language
Any C++ IDE (e.g., Code::Blocks, Visual Studio)
Computer with at least 4GB RAM and 2 GHz processor
Introduction
This experiment demonstrates the implementation of the Binary Search algorithm in C++. The Binary
Search algorithm is used to find the position of a target value within a sorted array. The algorithm
operates by dividing the search interval in half repeatedly until the target value is found or the interval
is empty. This experiment covers the working of Binary Search and the implementation in C++.
Description
Binary Search is a highly efficient algorithm that works only on sorted data. The key idea is to
repeatedly divide the search interval in half, checking whether the target value is in the left or right
half. By halving the search space with each comparison, Binary Search offers a time complexity of
O(log n), making it more efficient than linear search for large datasets.
The basic components of Binary Search include:
1. Low index: the starting point of the array.
2. High index: the ending point of the array.
3. Mid index: the midpoint calculated to divide the array into two halves.
Sample Input
cpp Copy
#include<iostream> using namespace std; int binarySearch(int arr[], int n, int target) {
int low = 0, high = n - 1; while (low <= high) { int mid = low + (high - low) / 2; if
(arr[mid] == target) { return mid; } if (arr[mid] < target) { low = mid + 1; } else {
high = mid - 1; } } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9, 11, 13}; int n
= sizeof(arr)/sizeof(arr[0]); int target = 7; int result = binarySearch(arr, n, target);
if(result != -1) cout << "Element found at index " << result << endl; else cout <<
"Element not found" << endl; return 0; }
Sample Output
mathematica Copy
Discussion/Conclusion
In this lab experiment, we performed the implementation of the Binary Search algorithm in C++. We
faced challenges regarding the correct implementation of the mid index and ensuring that the array
was sorted before performing the search. We used debugging tools and logical checks to ensure the
array was properly sorted and that the mid index was calculated correctly. Additionally, we learned the
importance of using Binary Search on sorted arrays to achieve the O(log n) time complexity.
The result confirmed that the Binary Search was implemented correctly, and the algorithm successfully
found the target element in the array. However, for unsorted data, the search did not work as
expected, which is a limitation of Binary Search.
In conclusion, we have successfully implemented Binary Search, and the experiment provided us with a
better understanding of its working and time complexity.