Binsearch
Anonymous
c_cpp
03/03/2026 5:17 AM
1.1 KB
15
Indexable
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter how many numbers: ";
cin >> n;
int arr[100]; // assuming max size 100
cout << "Enter " << n << " sorted numbers:\n";
for(int i = 0; i < n; i++) {
cin >> arr[i];
}
int target;
cout << "Enter the number to search: ";
cin >> target;
int low = 0, high = n - 1;
bool found = false;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == target) {
cout << "Number found at index " << mid << endl;
found = true;
break;
}
else if(arr[mid] < target) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
if(!found) {
cout << "Number NOT found." << endl;
}
return 0;
}Editor is loading...
Leave a Comment