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

Create binary_search.cpp #1993

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
45 changes: 45 additions & 0 deletions binary_search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// find middle term in the array, compare ,
// if not equal, check size and move left or right accordingly

#include <iostream>
using namespace std;

int binarySearch(int arr[],int size, int key){

int start = 0;
int end = size-1;

int mid= start + (end - start)/2;

while(start <= end){

if (arr[mid] == key){

return mid;
}

if (key > arr[mid]) {
start = mid + 1;
}
else{
end = mid - 1;
}

mid= start + (end - start)/2;
}

return -1;
}


int main(){

int even[6] = {2,4,6,8,12,18};
int odd[5] = {3,8,11,11,16};

int oddIndex = binarySearch( odd, 5, 11);

cout << "Index of 11 is " << oddIndex << "." << endl;

return 0;
}