Binary Search in C++17Binary search feedback and improvementsTemplate Binary Search TreeBinary search in C++Binary Search Implementation in C++C++ binary search treeSimple binary search in a vectorBinary Search Tree Implementation C++17Simple binary searchBinary Search Tree C++Binary search for students
Should I disclose a colleague's illness (that I should not know) when others badmouth him
Is neural networks training done one-by-one?
When and what was the first 3D acceleration device ever released?
The art of clickbait captions
Why does this if-statement combining assignment and an equality check return true?
Image processing: Removal of two spots in fundus images
Is it rude to call a professor by their last name with no prefix in a non-academic setting?
Are there any well known academic philosophy forums?
Adding spaces to string based on list
How to respond to an upset student?
I unknowingly submitted plagarised work
Did people go back to where they were?
Would jet fuel for an F-16 or F-35 be producible during WW2?
Is there a way to make it so the cursor is included when I prtscr key?
Is real public IP Address hidden when using a system wide proxy in Windows 10?
I think I may have violated academic integrity last year - what should I do?
Simple function that simulates survey results based on sample size and probability
What is the object moving across the ceiling in this stock footage?
How should I introduce map drawing to my players?
Python program to find the most frequent letter in a text
What are these arcade games in Ghostbusters 1984?
How to use Palladio font in text body but Computer Modern for Equations?
What was the idiom for something that we take without a doubt?
Is the field of q-series 'dead'?
Binary Search in C++17
Binary search feedback and improvementsTemplate Binary Search TreeBinary search in C++Binary Search Implementation in C++C++ binary search treeSimple binary search in a vectorBinary Search Tree Implementation C++17Simple binary searchBinary Search Tree C++Binary search for students
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
Question
Any way I can optimize this further with C++11 or C++17 features?
Would also like feedback on my variable naming, memory management, edge case handling (in this someone calling my function with an nullptr or int overflow with my rearranged equation to calculate the mid), and coding style. If there are other data structures I can use to implement this instead of basic arrays and raw pointers I'd like some feedback there too.
For my return type on the binary_search function, does it matter if I return a bool versus an int?
Code
#include <cassert>
#include <iostream>
bool binary_search(int* data, int num_elements, int target)
int low = 0;
int high = num_elements - 1;
int mid;
if(data == nullptr) throw std::exception();
while(low <= high)
mid = low + (high - low) / 2;
if(data[mid] == target)
return 1;
else if(data[mid] > target)
high = mid - 1;
else
low = mid + 1;
return 0;
int main()
int num_elements = 6;
int data[] = 5, 8, 10, 15, 26, 30 ;
int target[] = 5, 4, 12, 15, 35, 30 ;
int expected[] = 1, 0, 0, 1, 0, 1 ;
for(int i=0; i < num_elements; ++i)
try
assert(expected[i] == binary_search(data, num_elements, target[i]));
std::cout << expected[i] << " returned for search on " << target[i] << 'n';
catch(std::exception& e)
std::cout << "Exception " << e.what() << 'n';
return 0;
c++ binary-search c++17
$endgroup$
add a comment |
$begingroup$
Question
Any way I can optimize this further with C++11 or C++17 features?
Would also like feedback on my variable naming, memory management, edge case handling (in this someone calling my function with an nullptr or int overflow with my rearranged equation to calculate the mid), and coding style. If there are other data structures I can use to implement this instead of basic arrays and raw pointers I'd like some feedback there too.
For my return type on the binary_search function, does it matter if I return a bool versus an int?
Code
#include <cassert>
#include <iostream>
bool binary_search(int* data, int num_elements, int target)
int low = 0;
int high = num_elements - 1;
int mid;
if(data == nullptr) throw std::exception();
while(low <= high)
mid = low + (high - low) / 2;
if(data[mid] == target)
return 1;
else if(data[mid] > target)
high = mid - 1;
else
low = mid + 1;
return 0;
int main()
int num_elements = 6;
int data[] = 5, 8, 10, 15, 26, 30 ;
int target[] = 5, 4, 12, 15, 35, 30 ;
int expected[] = 1, 0, 0, 1, 0, 1 ;
for(int i=0; i < num_elements; ++i)
try
assert(expected[i] == binary_search(data, num_elements, target[i]));
std::cout << expected[i] << " returned for search on " << target[i] << 'n';
catch(std::exception& e)
std::cout << "Exception " << e.what() << 'n';
return 0;
c++ binary-search c++17
$endgroup$
add a comment |
$begingroup$
Question
Any way I can optimize this further with C++11 or C++17 features?
Would also like feedback on my variable naming, memory management, edge case handling (in this someone calling my function with an nullptr or int overflow with my rearranged equation to calculate the mid), and coding style. If there are other data structures I can use to implement this instead of basic arrays and raw pointers I'd like some feedback there too.
For my return type on the binary_search function, does it matter if I return a bool versus an int?
Code
#include <cassert>
#include <iostream>
bool binary_search(int* data, int num_elements, int target)
int low = 0;
int high = num_elements - 1;
int mid;
if(data == nullptr) throw std::exception();
while(low <= high)
mid = low + (high - low) / 2;
if(data[mid] == target)
return 1;
else if(data[mid] > target)
high = mid - 1;
else
low = mid + 1;
return 0;
int main()
int num_elements = 6;
int data[] = 5, 8, 10, 15, 26, 30 ;
int target[] = 5, 4, 12, 15, 35, 30 ;
int expected[] = 1, 0, 0, 1, 0, 1 ;
for(int i=0; i < num_elements; ++i)
try
assert(expected[i] == binary_search(data, num_elements, target[i]));
std::cout << expected[i] << " returned for search on " << target[i] << 'n';
catch(std::exception& e)
std::cout << "Exception " << e.what() << 'n';
return 0;
c++ binary-search c++17
$endgroup$
Question
Any way I can optimize this further with C++11 or C++17 features?
Would also like feedback on my variable naming, memory management, edge case handling (in this someone calling my function with an nullptr or int overflow with my rearranged equation to calculate the mid), and coding style. If there are other data structures I can use to implement this instead of basic arrays and raw pointers I'd like some feedback there too.
For my return type on the binary_search function, does it matter if I return a bool versus an int?
Code
#include <cassert>
#include <iostream>
bool binary_search(int* data, int num_elements, int target)
int low = 0;
int high = num_elements - 1;
int mid;
if(data == nullptr) throw std::exception();
while(low <= high)
mid = low + (high - low) / 2;
if(data[mid] == target)
return 1;
else if(data[mid] > target)
high = mid - 1;
else
low = mid + 1;
return 0;
int main()
int num_elements = 6;
int data[] = 5, 8, 10, 15, 26, 30 ;
int target[] = 5, 4, 12, 15, 35, 30 ;
int expected[] = 1, 0, 0, 1, 0, 1 ;
for(int i=0; i < num_elements; ++i)
try
assert(expected[i] == binary_search(data, num_elements, target[i]));
std::cout << expected[i] << " returned for search on " << target[i] << 'n';
catch(std::exception& e)
std::cout << "Exception " << e.what() << 'n';
return 0;
c++ binary-search c++17
c++ binary-search c++17
edited 4 hours ago
200_success
132k20160428
132k20160428
asked 8 hours ago
greggreg
450310
450310
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
An idiomatic approach
to implement this instead of basic arrays and raw pointers
is to use iterators.
Returning
boolis dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.All that said, consider the signature
template<typename It, typename T>
It binary_search(It first, It last, const T& target)It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.
$endgroup$
$begingroup$
Very very similar, now I pretty much have an implementation just as the same asbinary_findfrom thestd::lower_bounddocs you linked.
$endgroup$
– greg
5 hours ago
$begingroup$
Also forbinary_findfrom thestd::lower_bounddocs, is theComparetemplate even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to mywhile(low <= high)?
$endgroup$
– greg
4 hours ago
add a comment |
$begingroup$
Considering you are using the same numbers as their example, I assume you're already aware of the binary search algorithm.
Regarding coding style I prefer a space between flow control statements and the parenthesis but that is purely subjective.
Don't compare to
nullptr. Doif (!data)instead.IMO Not much use in printing out
what()if you don't provide (meaningful) messages along with your exception.
Could also specialize it.
e.g.:std::invalid_argument("no input provided").Could use brace initialization if you want to use more modern C++ features (nitpick:
midis not initialized).Why didn't you use
vector? It's pretty much a drop-in replacment. You could then also use the range for loop.return 0is implicit inmain.
$endgroup$
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initializationint data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializingmidto 0, any negative implication to not initializing it? To optimize I will switch tovectorI had no strong reason behind using an array.
$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leavingmiduninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term.std::vectorwhere a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.
$endgroup$
– Deduplicator
3 hours ago
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220992%2fbinary-search-in-c17%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
An idiomatic approach
to implement this instead of basic arrays and raw pointers
is to use iterators.
Returning
boolis dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.All that said, consider the signature
template<typename It, typename T>
It binary_search(It first, It last, const T& target)It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.
$endgroup$
$begingroup$
Very very similar, now I pretty much have an implementation just as the same asbinary_findfrom thestd::lower_bounddocs you linked.
$endgroup$
– greg
5 hours ago
$begingroup$
Also forbinary_findfrom thestd::lower_bounddocs, is theComparetemplate even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to mywhile(low <= high)?
$endgroup$
– greg
4 hours ago
add a comment |
$begingroup$
An idiomatic approach
to implement this instead of basic arrays and raw pointers
is to use iterators.
Returning
boolis dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.All that said, consider the signature
template<typename It, typename T>
It binary_search(It first, It last, const T& target)It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.
$endgroup$
$begingroup$
Very very similar, now I pretty much have an implementation just as the same asbinary_findfrom thestd::lower_bounddocs you linked.
$endgroup$
– greg
5 hours ago
$begingroup$
Also forbinary_findfrom thestd::lower_bounddocs, is theComparetemplate even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to mywhile(low <= high)?
$endgroup$
– greg
4 hours ago
add a comment |
$begingroup$
An idiomatic approach
to implement this instead of basic arrays and raw pointers
is to use iterators.
Returning
boolis dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.All that said, consider the signature
template<typename It, typename T>
It binary_search(It first, It last, const T& target)It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.
$endgroup$
An idiomatic approach
to implement this instead of basic arrays and raw pointers
is to use iterators.
Returning
boolis dubious. The situation where I only want to know if the element is present or not is very rare. Typically I want to know where exactly the element is (or, if absent, where it should be inserted to keep the collection sorted). Your function does compute this information, but immediately throws it away. Return an iterator.All that said, consider the signature
template<typename It, typename T>
It binary_search(It first, It last, const T& target)It is now suspiciously similar to the standard library's std::lower_bound. Follow the link for further insight and inspiration.
edited 4 hours ago
Deduplicator
12.4k2052
12.4k2052
answered 6 hours ago
vnpvnp
41.1k234104
41.1k234104
$begingroup$
Very very similar, now I pretty much have an implementation just as the same asbinary_findfrom thestd::lower_bounddocs you linked.
$endgroup$
– greg
5 hours ago
$begingroup$
Also forbinary_findfrom thestd::lower_bounddocs, is theComparetemplate even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to mywhile(low <= high)?
$endgroup$
– greg
4 hours ago
add a comment |
$begingroup$
Very very similar, now I pretty much have an implementation just as the same asbinary_findfrom thestd::lower_bounddocs you linked.
$endgroup$
– greg
5 hours ago
$begingroup$
Also forbinary_findfrom thestd::lower_bounddocs, is theComparetemplate even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to mywhile(low <= high)?
$endgroup$
– greg
4 hours ago
$begingroup$
Very very similar, now I pretty much have an implementation just as the same as
binary_find from the std::lower_bound docs you linked.$endgroup$
– greg
5 hours ago
$begingroup$
Very very similar, now I pretty much have an implementation just as the same as
binary_find from the std::lower_bound docs you linked.$endgroup$
– greg
5 hours ago
$begingroup$
Also for
binary_find from the std::lower_bound docs, is the Compare template even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to my while(low <= high)?$endgroup$
– greg
4 hours ago
$begingroup$
Also for
binary_find from the std::lower_bound docs, is the Compare template even needed, I suspected it may not be, removed it in my implementation and the code appears to run the same as expected? Is this compare equivalent to my while(low <= high)?$endgroup$
– greg
4 hours ago
add a comment |
$begingroup$
Considering you are using the same numbers as their example, I assume you're already aware of the binary search algorithm.
Regarding coding style I prefer a space between flow control statements and the parenthesis but that is purely subjective.
Don't compare to
nullptr. Doif (!data)instead.IMO Not much use in printing out
what()if you don't provide (meaningful) messages along with your exception.
Could also specialize it.
e.g.:std::invalid_argument("no input provided").Could use brace initialization if you want to use more modern C++ features (nitpick:
midis not initialized).Why didn't you use
vector? It's pretty much a drop-in replacment. You could then also use the range for loop.return 0is implicit inmain.
$endgroup$
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initializationint data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializingmidto 0, any negative implication to not initializing it? To optimize I will switch tovectorI had no strong reason behind using an array.
$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leavingmiduninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term.std::vectorwhere a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.
$endgroup$
– Deduplicator
3 hours ago
add a comment |
$begingroup$
Considering you are using the same numbers as their example, I assume you're already aware of the binary search algorithm.
Regarding coding style I prefer a space between flow control statements and the parenthesis but that is purely subjective.
Don't compare to
nullptr. Doif (!data)instead.IMO Not much use in printing out
what()if you don't provide (meaningful) messages along with your exception.
Could also specialize it.
e.g.:std::invalid_argument("no input provided").Could use brace initialization if you want to use more modern C++ features (nitpick:
midis not initialized).Why didn't you use
vector? It's pretty much a drop-in replacment. You could then also use the range for loop.return 0is implicit inmain.
$endgroup$
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initializationint data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializingmidto 0, any negative implication to not initializing it? To optimize I will switch tovectorI had no strong reason behind using an array.
$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leavingmiduninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term.std::vectorwhere a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.
$endgroup$
– Deduplicator
3 hours ago
add a comment |
$begingroup$
Considering you are using the same numbers as their example, I assume you're already aware of the binary search algorithm.
Regarding coding style I prefer a space between flow control statements and the parenthesis but that is purely subjective.
Don't compare to
nullptr. Doif (!data)instead.IMO Not much use in printing out
what()if you don't provide (meaningful) messages along with your exception.
Could also specialize it.
e.g.:std::invalid_argument("no input provided").Could use brace initialization if you want to use more modern C++ features (nitpick:
midis not initialized).Why didn't you use
vector? It's pretty much a drop-in replacment. You could then also use the range for loop.return 0is implicit inmain.
$endgroup$
Considering you are using the same numbers as their example, I assume you're already aware of the binary search algorithm.
Regarding coding style I prefer a space between flow control statements and the parenthesis but that is purely subjective.
Don't compare to
nullptr. Doif (!data)instead.IMO Not much use in printing out
what()if you don't provide (meaningful) messages along with your exception.
Could also specialize it.
e.g.:std::invalid_argument("no input provided").Could use brace initialization if you want to use more modern C++ features (nitpick:
midis not initialized).Why didn't you use
vector? It's pretty much a drop-in replacment. You could then also use the range for loop.return 0is implicit inmain.
answered 6 hours ago
yuriyuri
3,89721235
3,89721235
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initializationint data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializingmidto 0, any negative implication to not initializing it? To optimize I will switch tovectorI had no strong reason behind using an array.
$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leavingmiduninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term.std::vectorwhere a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.
$endgroup$
– Deduplicator
3 hours ago
add a comment |
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initializationint data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializingmidto 0, any negative implication to not initializing it? To optimize I will switch tovectorI had no strong reason behind using an array.
$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leavingmiduninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term.std::vectorwhere a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.
$endgroup$
– Deduplicator
3 hours ago
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initialization
int data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializing mid to 0, any negative implication to not initializing it? To optimize I will switch to vector I had no strong reason behind using an array.$endgroup$
– greg
5 hours ago
$begingroup$
Is brace initialization preferred and why? Is this not an example of brace initialization
int data[] = 5, 8, 10, 15, 26, 30 ;? I debated on initializing mid to 0, any negative implication to not initializing it? To optimize I will switch to vector I had no strong reason behind using an array.$endgroup$
– greg
5 hours ago
$begingroup$
How should he avoid leaving
mid uninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term. std::vector where a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.$endgroup$
– Deduplicator
3 hours ago
$begingroup$
How should he avoid leaving
mid uninitialized on declaration? A bit more meat please. Brace-initialization? Whatever… and it's the wrong term. std::vector where a raw array works? No, even if the compiler could in theory optimize it all away. Also, it is perfectly for-range compatible.$endgroup$
– Deduplicator
3 hours ago
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f220992%2fbinary-search-in-c17%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown