Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

OPTIMISED CODE FOR binary_search.cpp #2318

Open
SamyakMishra072 opened this issue Oct 5, 2024 · 0 comments
Open

OPTIMISED CODE FOR binary_search.cpp #2318

SamyakMishra072 opened this issue Oct 5, 2024 · 0 comments

Comments

@SamyakMishra072
Copy link

OPTIMISED CODE FOR binary_search.cpp

#include
using namespace std;

int binarySearch(int a[], int l, int r, int x);

int main()
{
int n;
cin >> n;
int a[n];
for(int i = 0; i < n; i++)
cin >> a[i];
int x;
cin >> x;
int result = binarySearch(a, 0, n - 1, x);
if(result == -1)
cout << "Not found";
else
cout << "Found";
return 0;
}
int binarySearch(int a[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;

    if (a[mid] == x) 
        return mid; 

    
    if (a[mid] > x) 
        return binarySearch(a, l, mid - 1, x); 

    return binarySearch(a, mid + 1, r, x); 
}   
return -1; 

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant