Skip to content

Update binary_search.cpp #345

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 11 additions & 22 deletions algorithms/searches/binary_search.cpp
Original file line number Diff line number Diff line change
@@ -1,30 +1,19 @@
//
// Binary Search implemented in C++
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/searches/binary-search
// https://github.com/allalgorithms/cpp
// https://repl.it/@abranhe/Binary-Search
//
// Contributed by: Carlos Abraham Hernandez
// Github: @abranhe
//
#include <iostream>

using namespace std;

int binary_search(int a[],int l,int r,int key)
{
while(l<=r)
{
int m = l + (r-l) / 2;
int mid = l + (r-l) / 2;

if(key == a[m])
return m;
else if(key < a[m])
r = m-1;
if(key == a[mid])
return mid;
else if(key < a[mid])
r = mid-1;
else
l = m+1;
l = mid+1;
}
return -1;
}
Expand All @@ -47,8 +36,8 @@ int main(int argc, char const *argv[])
int res = binary_search(a, 0, n-1, key);

if(res != -1)
cout<< key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
cout<< key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
}