Hi
- User
Hi
- Assistant
Hello! How can I assist you today?
- User
Can you check my Binary Search Algorithm? #include <bits/stdc++.h> using namespace std;
long long Binary_Search(long long a[], long long b, long long n) { if(a[0] == b || a[n-1] == b) return 1; int left,right,middle; left = a[0]; right = a[n-1]; while(left<=right){ middle = (left+right)/2; if( a[middle] == b ) return 1; if(a[middle] < b) left = middle + 1; else right = middle-1; } return 0; }
int main(){ long long n,m; cin >> n >> m; long long a[100000]; for(int i = 0; i<n; i++) cin >> a[i]; while(m>0){ long long k; cin >> k; cout << Binary_Search(a,k,n) ; m--; } }
- Assistant
Your Binary Search algorithm looks mostly correct. However, there are a few points that need to be addressed:
- The size of the array
ais fixed at 100000. If the input size exceeds 100000, it will cause a runtime error. It would be better to dynamically allocate memory for the array based on the value ofn. - The variables
left,right, andmiddleare of typeint. They should be of typelong longto match the array elements and the search value. - In the while loop condition, instead of , it should be because if the search value is not found in the array, will eventually become greater than .
- The size of the array
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.