-
Notifications
You must be signed in to change notification settings - Fork 497
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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) | ||
{ | ||
while(end >= start) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please make this, |
||
{ | ||
int mid = start + (end - start)/2; | ||
if(array[mid] == find) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
return mid; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add whitespace around binary operator |
||
else if(array[mid] < find) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
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; | ||
} |
There was a problem hiding this comment.
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.