CAP770 Advanced Data Structure and Algorithm Ca1 Vaishnavi
The document presents a lab evaluation for the CAP770 Advanced Data Structure and Algorithm course, authored by Vaishnavi Sharma. It includes a recursive implementation of the Binary Search algorithm in C++, demonstrating how to find a target element in a sorted array. The code also handles cases where the target element is not present in the array.
CAP770 Advanced Data Structure and Algorithm Ca1 Vaishnavi
The document presents a lab evaluation for the CAP770 Advanced Data Structure and Algorithm course, authored by Vaishnavi Sharma. It includes a recursive implementation of the Binary Search algorithm in C++, demonstrating how to find a target element in a sorted array. The code also handles cases where the target element is not present in the array.
ANS: #include <iostream> using namespace std; int binarySearch(int arr[], int left, int right, int target) { if (right >= left) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; }
if (arr[mid] > target) {
return binarySearch(arr, left, mid - 1, target); } return binarySearch(arr, mid + 1, right, target); } return -1; } int main() { int arr[] = { 2, 3, 4, 10, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int target = 10; int result = binarySearch(arr, 0, n - 1, target); if (result == -1) { cout << "Element not present in array" << endl; } else { cout << "Element found at index " << result << endl; } return 0; }