-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.cpp
More file actions
39 lines (31 loc) · 957 Bytes
/
3.cpp
File metadata and controls
39 lines (31 loc) · 957 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
using namespace std;
// Function for binary search
int binarySearch(int arr[], int size, int target) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // Prevent overflow
if (arr[mid] == target) {
return mid; // Target found
} else if (arr[mid] < target) {
low = mid + 1; // Target is in the right half
} else {
high = mid - 1; // Target is in the left half
}
}
return -1; // Target not found
}
int main() {
int arr[] = {2, 3, 4, 10, 40}; // Sorted array
int size = sizeof(arr) / sizeof(arr[0]);
int target;
cout << "Enter the number to search: ";
cin >> target;
int result = binarySearch(arr, size, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found." << endl;
}
return 0;
}