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

Added Binary Search [C++] #550

Closed
wants to merge 4 commits into from
Closed
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
42 changes: 42 additions & 0 deletions binary_search/binarysearch.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#include<iostream>

using namespace std;

int binary_search_iterative(int array[], int start, int end, int find)
{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The indentation is not according to standard cpp guidelines.
The opening curly brace always starts in same line.
int name_of_func(...) { Same changes in rest of the file.

while(end >= start)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please make this, while (...) { as per standard cpp guidelines. Same changes in rest of the file.

{
int mid = start + (end - start)/2;
if(array[mid] == find)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if (...) { Same changes in rest of the file.

return mid;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add whitespace around binary operator /. Same changes in rest of the file.

else if(array[mid] < find)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

else if (...) { Same changes in rest of the file.

start = mid + 1;
else
end = mid - 1;
}
return -1;
}

int binary_search_recursive(int array[], int start, int end, int find)
{
if(end >= start)
{
int mid = start + (end - start)/2;
if(array[mid] == find)
return mid;
else if(array[mid] > find)
return binary_search_recursive(array, start, mid - 1, find);
else
return binary_search_recursive(array, mid + 1, end, find);
}
return -1;
}

int main()
{
int array[] = { 1, 2, 3, 4, 5, 6, 11, 23, 25, 66, 88, 99, 113 };
int end = sizeof(array)/sizeof(array[0]);
cout << binary_search_iterative(array,0,end,1) << '\n' << binary_search_recursive(array,0,end,1) << '\n';
cout << binary_search_iterative(array,0,end,0) << '\n' << binary_search_recursive(array,0,end,0) << '\n';
return 0;
}