Cycle 01
Lab Cycle 1 — Arrays & Searching
Binary Search
Problem Statement
Write a program to implement binary search on a sorted array.
#include <iostream>
using namespace std;
int binarySearch(int arr[], int l, int r, int key) {
while (l <= r) {
int mid = l + (r - l) / 2;
if (arr[mid] == key) return mid;
if (arr[mid] < key) l = mid + 1;
else r = mid - 1;
}
return -1;
}
int main() {
int arr[] = {10, 20, 30, 40, 50};
int key = 40;
int result = binarySearch(arr, 0, 4, key);
cout << "Found at index " << result;
return 0;
}
Question 2 of 5