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

Can we completely replace inheritance using strategy pattern and dependency injection?

Why are MBA programs closing in the United States?

Was Self-modifying-code possible just using BASIC?

Why is long-term living in Almost-Earth causing severe health problems?

The usage of kelvin in formulas

Why is Na5 not played in this line of the French Defense, Advance Variation?

Proving that a Russian cryptographic standard is too structured

How can I make 12 tone and atonal melodies sound interesting?

How do i export activities related to an account with a specific recordtype?

Does putting salt first make it easier for attacker to bruteforce the hash?

How to publish items after pipeline is finished?

Is Lambda Calculus purely syntactic?

Who is "He that flies" in Lord of the Rings?

Why was this person allowed to become Grand Maester?

Why Does Mama Coco Look Old After Going to the Other World?

Why do radiation hardened IC packages often have long leads?

Who voices the small round football sized demon in Good Omens?

Possible runaway argument using circuitikz

Why did the World Bank set the global poverty line at $1.90?

Ability To Change Root User Password (Vulnerability?)

Grep Match and extract

Is it okay to have a sequel start immediately after the end of the first book?

Analogy between an unknown in an argument, and a contradiction in the principle of explosion

What does the pair of vertical lines in empirical entropy formula mean?



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;








9












$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;










share|improve this question











$endgroup$







  • 4




    $begingroup$
    That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
    $endgroup$
    – Bob Jarvis
    May 26 at 13:29






  • 1




    $begingroup$
    I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
    $endgroup$
    – greg
    May 26 at 16:33






  • 1




    $begingroup$
    You could optimize it by using a standard algorithm: std::lower_bound()
    $endgroup$
    – Martin York
    May 30 at 19:33

















9












$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;










share|improve this question











$endgroup$







  • 4




    $begingroup$
    That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
    $endgroup$
    – Bob Jarvis
    May 26 at 13:29






  • 1




    $begingroup$
    I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
    $endgroup$
    – greg
    May 26 at 16:33






  • 1




    $begingroup$
    You could optimize it by using a standard algorithm: std::lower_bound()
    $endgroup$
    – Martin York
    May 30 at 19:33













9












9








9


1



$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;










share|improve this question











$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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 25 at 18:51









200_success

133k20163433




133k20163433










asked May 25 at 14:41









greggreg

532310




532310







  • 4




    $begingroup$
    That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
    $endgroup$
    – Bob Jarvis
    May 26 at 13:29






  • 1




    $begingroup$
    I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
    $endgroup$
    – greg
    May 26 at 16:33






  • 1




    $begingroup$
    You could optimize it by using a standard algorithm: std::lower_bound()
    $endgroup$
    – Martin York
    May 30 at 19:33












  • 4




    $begingroup$
    That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
    $endgroup$
    – Bob Jarvis
    May 26 at 13:29






  • 1




    $begingroup$
    I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
    $endgroup$
    – greg
    May 26 at 16:33






  • 1




    $begingroup$
    You could optimize it by using a standard algorithm: std::lower_bound()
    $endgroup$
    – Martin York
    May 30 at 19:33







4




4




$begingroup$
That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
$endgroup$
– Bob Jarvis
May 26 at 13:29




$begingroup$
That depends. What are you optimizing for? Runtime? CPU cycles? Memory usage? Minimal (or maximal) chance of attracting the attention of demonic entities from the 12th dimension? ???
$endgroup$
– Bob Jarvis
May 26 at 13:29




1




1




$begingroup$
I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
$endgroup$
– greg
May 26 at 16:33




$begingroup$
I want to optimize for runtime, great point I should call this out more explicitly in future posts... well if those entities produce this stardewvalleywiki.com/Void_Essence. Yes.Yes I do want to attract them.
$endgroup$
– greg
May 26 at 16:33




1




1




$begingroup$
You could optimize it by using a standard algorithm: std::lower_bound()
$endgroup$
– Martin York
May 30 at 19:33




$begingroup$
You could optimize it by using a standard algorithm: std::lower_bound()
$endgroup$
– Martin York
May 30 at 19:33










3 Answers
3






active

oldest

votes


















14












$begingroup$


  • An idiomatic approach




    to implement this instead of basic arrays and raw pointers




    is to use iterators.



  • Returning bool is 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.







share|improve this answer











$endgroup$












  • $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
    May 25 at 17:58










  • $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
    May 25 at 18:14







  • 1




    $begingroup$
    @greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
    $endgroup$
    – Kyle
    May 26 at 1:13






  • 2




    $begingroup$
    Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
    $endgroup$
    – Rakete1111
    May 26 at 6:28






  • 3




    $begingroup$
    @greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
    $endgroup$
    – Rakete1111
    May 26 at 13:33



















7












$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. Do if (!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: mid is 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 0 is implicit in main.






share|improve this answer









$endgroup$












  • $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
    May 25 at 18:04










  • $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
    May 25 at 19:51






  • 1




    $begingroup$
    Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
    $endgroup$
    – glaba
    May 26 at 6:10










  • $begingroup$
    @glaba Interesting, can you provide examples where that is the case?
    $endgroup$
    – yuri
    May 26 at 6:31










  • $begingroup$
    @glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
    $endgroup$
    – ComFreek
    May 26 at 12:24



















4












$begingroup$

In the if/else statement, I would put the most frequently true conditions at the top to reduce the amount of condition checking. Is it really more common for data[mid] to equal target than for it to be greater than or less than it? I doubt it, so I'd reorder the blocks to something like:



if (data[mid] > target) 
high = mid - 1;
else if(data[mid] < target)
low = mid + 1;
else
return true;



You could also reduce hard coding by replacing num_elements with std::size(data).



Returning true or false is more readable than returning 1 or 0. It expresses the function's purpose more clearly and avoids confusion.



Finally, replacing the division by 2 with a bit shift might not help but it's worth testing if this is performance-critical:



mid = low + ((high - low) >> 1); // ">> 1" is "/ 2"


EDIT: On Clang, bit shifting actually does help (GCC gives the optimization either way), but you can get the same benefit by appending a u to the 2, which is more readable anyway. 2u is unsigned, so it causes (high - low) to also be cast to unsigned, which tells Clang that it's never negative (which GCC already deduced from your while condition) and that a bit shift is therefore safe to do on it. You can also simplify the arithmetic a little since you're just calculating an average. These two tweaks reduce the assembly for this line to just 2 instructions (down from 7 on Clang or 4 on GCC):



mid = (high + low) / 2u;





share|improve this answer











$endgroup$








  • 3




    $begingroup$
    I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
    $endgroup$
    – L. F.
    May 26 at 3:20






  • 1




    $begingroup$
    @L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
    $endgroup$
    – Gumby The Green
    May 26 at 4:10







  • 1




    $begingroup$
    I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
    $endgroup$
    – Yet Another User
    May 26 at 6:12






  • 3




    $begingroup$
    @CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
    $endgroup$
    – Gumby The Green
    May 26 at 10:38







  • 1




    $begingroup$
    Note that the expression (high + low) may overflow.
    $endgroup$
    – Carsten S
    May 26 at 13:26











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
);



);













draft saved

draft discarded


















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

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









14












$begingroup$


  • An idiomatic approach




    to implement this instead of basic arrays and raw pointers




    is to use iterators.



  • Returning bool is 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.







share|improve this answer











$endgroup$












  • $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
    May 25 at 17:58










  • $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
    May 25 at 18:14







  • 1




    $begingroup$
    @greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
    $endgroup$
    – Kyle
    May 26 at 1:13






  • 2




    $begingroup$
    Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
    $endgroup$
    – Rakete1111
    May 26 at 6:28






  • 3




    $begingroup$
    @greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
    $endgroup$
    – Rakete1111
    May 26 at 13:33
















14












$begingroup$


  • An idiomatic approach




    to implement this instead of basic arrays and raw pointers




    is to use iterators.



  • Returning bool is 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.







share|improve this answer











$endgroup$












  • $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
    May 25 at 17:58










  • $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
    May 25 at 18:14







  • 1




    $begingroup$
    @greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
    $endgroup$
    – Kyle
    May 26 at 1:13






  • 2




    $begingroup$
    Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
    $endgroup$
    – Rakete1111
    May 26 at 6:28






  • 3




    $begingroup$
    @greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
    $endgroup$
    – Rakete1111
    May 26 at 13:33














14












14








14





$begingroup$


  • An idiomatic approach




    to implement this instead of basic arrays and raw pointers




    is to use iterators.



  • Returning bool is 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.







share|improve this answer











$endgroup$




  • An idiomatic approach




    to implement this instead of basic arrays and raw pointers




    is to use iterators.



  • Returning bool is 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.








share|improve this answer














share|improve this answer



share|improve this answer








edited May 25 at 19:04









Deduplicator

12.7k2052




12.7k2052










answered May 25 at 16:34









vnpvnp

41.5k234106




41.5k234106











  • $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
    May 25 at 17:58










  • $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
    May 25 at 18:14







  • 1




    $begingroup$
    @greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
    $endgroup$
    – Kyle
    May 26 at 1:13






  • 2




    $begingroup$
    Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
    $endgroup$
    – Rakete1111
    May 26 at 6:28






  • 3




    $begingroup$
    @greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
    $endgroup$
    – Rakete1111
    May 26 at 13:33

















  • $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
    May 25 at 17:58










  • $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
    May 25 at 18:14







  • 1




    $begingroup$
    @greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
    $endgroup$
    – Kyle
    May 26 at 1:13






  • 2




    $begingroup$
    Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
    $endgroup$
    – Rakete1111
    May 26 at 6:28






  • 3




    $begingroup$
    @greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
    $endgroup$
    – Rakete1111
    May 26 at 13:33
















$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
May 25 at 17:58




$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
May 25 at 17:58












$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
May 25 at 18:14





$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
May 25 at 18:14





1




1




$begingroup$
@greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
$endgroup$
– Kyle
May 26 at 1:13




$begingroup$
@greg By default, std::lower_bound and its companions use operator< to do comparisons. The compare template allows the caller to change the comparison function (for example if the data you're searching doesn't overload operator<).
$endgroup$
– Kyle
May 26 at 1:13




2




2




$begingroup$
Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
$endgroup$
– Rakete1111
May 26 at 6:28




$begingroup$
Isn't OP's algorithm a std::binary_search? I don't see this is a lower bound.
$endgroup$
– Rakete1111
May 26 at 6:28




3




3




$begingroup$
@greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
$endgroup$
– Rakete1111
May 26 at 13:33





$begingroup$
@greg lower bound returns the first element that is greater than target; your algorithm searches for an exact match.
$endgroup$
– Rakete1111
May 26 at 13:33














7












$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. Do if (!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: mid is 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 0 is implicit in main.






share|improve this answer









$endgroup$












  • $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
    May 25 at 18:04










  • $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
    May 25 at 19:51






  • 1




    $begingroup$
    Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
    $endgroup$
    – glaba
    May 26 at 6:10










  • $begingroup$
    @glaba Interesting, can you provide examples where that is the case?
    $endgroup$
    – yuri
    May 26 at 6:31










  • $begingroup$
    @glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
    $endgroup$
    – ComFreek
    May 26 at 12:24
















7












$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. Do if (!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: mid is 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 0 is implicit in main.






share|improve this answer









$endgroup$












  • $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
    May 25 at 18:04










  • $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
    May 25 at 19:51






  • 1




    $begingroup$
    Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
    $endgroup$
    – glaba
    May 26 at 6:10










  • $begingroup$
    @glaba Interesting, can you provide examples where that is the case?
    $endgroup$
    – yuri
    May 26 at 6:31










  • $begingroup$
    @glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
    $endgroup$
    – ComFreek
    May 26 at 12:24














7












7








7





$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. Do if (!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: mid is 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 0 is implicit in main.






share|improve this answer









$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. Do if (!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: mid is 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 0 is implicit in main.







share|improve this answer












share|improve this answer



share|improve this answer










answered May 25 at 16:27









yuriyuri

4,06221236




4,06221236











  • $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
    May 25 at 18:04










  • $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
    May 25 at 19:51






  • 1




    $begingroup$
    Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
    $endgroup$
    – glaba
    May 26 at 6:10










  • $begingroup$
    @glaba Interesting, can you provide examples where that is the case?
    $endgroup$
    – yuri
    May 26 at 6:31










  • $begingroup$
    @glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
    $endgroup$
    – ComFreek
    May 26 at 12:24

















  • $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
    May 25 at 18:04










  • $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
    May 25 at 19:51






  • 1




    $begingroup$
    Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
    $endgroup$
    – glaba
    May 26 at 6:10










  • $begingroup$
    @glaba Interesting, can you provide examples where that is the case?
    $endgroup$
    – yuri
    May 26 at 6:31










  • $begingroup$
    @glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
    $endgroup$
    – ComFreek
    May 26 at 12:24
















$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
May 25 at 18:04




$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
May 25 at 18:04












$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
May 25 at 19:51




$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
May 25 at 19:51




1




1




$begingroup$
Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
$endgroup$
– glaba
May 26 at 6:10




$begingroup$
Technically, nullptr does not necessarily have to be equal to 0, it is OS specific. So, I don't know if it's a good idea to use !data instead of comparing to nullptr
$endgroup$
– glaba
May 26 at 6:10












$begingroup$
@glaba Interesting, can you provide examples where that is the case?
$endgroup$
– yuri
May 26 at 6:31




$begingroup$
@glaba Interesting, can you provide examples where that is the case?
$endgroup$
– yuri
May 26 at 6:31












$begingroup$
@glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
$endgroup$
– ComFreek
May 26 at 12:24





$begingroup$
@glaba if(!data) is equivalent to if (data == nullptr), see Can I use if (pointer) instead of if (pointer != NULL)?.
$endgroup$
– ComFreek
May 26 at 12:24












4












$begingroup$

In the if/else statement, I would put the most frequently true conditions at the top to reduce the amount of condition checking. Is it really more common for data[mid] to equal target than for it to be greater than or less than it? I doubt it, so I'd reorder the blocks to something like:



if (data[mid] > target) 
high = mid - 1;
else if(data[mid] < target)
low = mid + 1;
else
return true;



You could also reduce hard coding by replacing num_elements with std::size(data).



Returning true or false is more readable than returning 1 or 0. It expresses the function's purpose more clearly and avoids confusion.



Finally, replacing the division by 2 with a bit shift might not help but it's worth testing if this is performance-critical:



mid = low + ((high - low) >> 1); // ">> 1" is "/ 2"


EDIT: On Clang, bit shifting actually does help (GCC gives the optimization either way), but you can get the same benefit by appending a u to the 2, which is more readable anyway. 2u is unsigned, so it causes (high - low) to also be cast to unsigned, which tells Clang that it's never negative (which GCC already deduced from your while condition) and that a bit shift is therefore safe to do on it. You can also simplify the arithmetic a little since you're just calculating an average. These two tweaks reduce the assembly for this line to just 2 instructions (down from 7 on Clang or 4 on GCC):



mid = (high + low) / 2u;





share|improve this answer











$endgroup$








  • 3




    $begingroup$
    I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
    $endgroup$
    – L. F.
    May 26 at 3:20






  • 1




    $begingroup$
    @L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
    $endgroup$
    – Gumby The Green
    May 26 at 4:10







  • 1




    $begingroup$
    I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
    $endgroup$
    – Yet Another User
    May 26 at 6:12






  • 3




    $begingroup$
    @CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
    $endgroup$
    – Gumby The Green
    May 26 at 10:38







  • 1




    $begingroup$
    Note that the expression (high + low) may overflow.
    $endgroup$
    – Carsten S
    May 26 at 13:26















4












$begingroup$

In the if/else statement, I would put the most frequently true conditions at the top to reduce the amount of condition checking. Is it really more common for data[mid] to equal target than for it to be greater than or less than it? I doubt it, so I'd reorder the blocks to something like:



if (data[mid] > target) 
high = mid - 1;
else if(data[mid] < target)
low = mid + 1;
else
return true;



You could also reduce hard coding by replacing num_elements with std::size(data).



Returning true or false is more readable than returning 1 or 0. It expresses the function's purpose more clearly and avoids confusion.



Finally, replacing the division by 2 with a bit shift might not help but it's worth testing if this is performance-critical:



mid = low + ((high - low) >> 1); // ">> 1" is "/ 2"


EDIT: On Clang, bit shifting actually does help (GCC gives the optimization either way), but you can get the same benefit by appending a u to the 2, which is more readable anyway. 2u is unsigned, so it causes (high - low) to also be cast to unsigned, which tells Clang that it's never negative (which GCC already deduced from your while condition) and that a bit shift is therefore safe to do on it. You can also simplify the arithmetic a little since you're just calculating an average. These two tweaks reduce the assembly for this line to just 2 instructions (down from 7 on Clang or 4 on GCC):



mid = (high + low) / 2u;





share|improve this answer











$endgroup$








  • 3




    $begingroup$
    I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
    $endgroup$
    – L. F.
    May 26 at 3:20






  • 1




    $begingroup$
    @L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
    $endgroup$
    – Gumby The Green
    May 26 at 4:10







  • 1




    $begingroup$
    I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
    $endgroup$
    – Yet Another User
    May 26 at 6:12






  • 3




    $begingroup$
    @CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
    $endgroup$
    – Gumby The Green
    May 26 at 10:38







  • 1




    $begingroup$
    Note that the expression (high + low) may overflow.
    $endgroup$
    – Carsten S
    May 26 at 13:26













4












4








4





$begingroup$

In the if/else statement, I would put the most frequently true conditions at the top to reduce the amount of condition checking. Is it really more common for data[mid] to equal target than for it to be greater than or less than it? I doubt it, so I'd reorder the blocks to something like:



if (data[mid] > target) 
high = mid - 1;
else if(data[mid] < target)
low = mid + 1;
else
return true;



You could also reduce hard coding by replacing num_elements with std::size(data).



Returning true or false is more readable than returning 1 or 0. It expresses the function's purpose more clearly and avoids confusion.



Finally, replacing the division by 2 with a bit shift might not help but it's worth testing if this is performance-critical:



mid = low + ((high - low) >> 1); // ">> 1" is "/ 2"


EDIT: On Clang, bit shifting actually does help (GCC gives the optimization either way), but you can get the same benefit by appending a u to the 2, which is more readable anyway. 2u is unsigned, so it causes (high - low) to also be cast to unsigned, which tells Clang that it's never negative (which GCC already deduced from your while condition) and that a bit shift is therefore safe to do on it. You can also simplify the arithmetic a little since you're just calculating an average. These two tweaks reduce the assembly for this line to just 2 instructions (down from 7 on Clang or 4 on GCC):



mid = (high + low) / 2u;





share|improve this answer











$endgroup$



In the if/else statement, I would put the most frequently true conditions at the top to reduce the amount of condition checking. Is it really more common for data[mid] to equal target than for it to be greater than or less than it? I doubt it, so I'd reorder the blocks to something like:



if (data[mid] > target) 
high = mid - 1;
else if(data[mid] < target)
low = mid + 1;
else
return true;



You could also reduce hard coding by replacing num_elements with std::size(data).



Returning true or false is more readable than returning 1 or 0. It expresses the function's purpose more clearly and avoids confusion.



Finally, replacing the division by 2 with a bit shift might not help but it's worth testing if this is performance-critical:



mid = low + ((high - low) >> 1); // ">> 1" is "/ 2"


EDIT: On Clang, bit shifting actually does help (GCC gives the optimization either way), but you can get the same benefit by appending a u to the 2, which is more readable anyway. 2u is unsigned, so it causes (high - low) to also be cast to unsigned, which tells Clang that it's never negative (which GCC already deduced from your while condition) and that a bit shift is therefore safe to do on it. You can also simplify the arithmetic a little since you're just calculating an average. These two tweaks reduce the assembly for this line to just 2 instructions (down from 7 on Clang or 4 on GCC):



mid = (high + low) / 2u;






share|improve this answer














share|improve this answer



share|improve this answer








edited May 26 at 11:04

























answered May 26 at 3:17









Gumby The GreenGumby The Green

413




413







  • 3




    $begingroup$
    I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
    $endgroup$
    – L. F.
    May 26 at 3:20






  • 1




    $begingroup$
    @L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
    $endgroup$
    – Gumby The Green
    May 26 at 4:10







  • 1




    $begingroup$
    I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
    $endgroup$
    – Yet Another User
    May 26 at 6:12






  • 3




    $begingroup$
    @CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
    $endgroup$
    – Gumby The Green
    May 26 at 10:38







  • 1




    $begingroup$
    Note that the expression (high + low) may overflow.
    $endgroup$
    – Carsten S
    May 26 at 13:26












  • 3




    $begingroup$
    I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
    $endgroup$
    – L. F.
    May 26 at 3:20






  • 1




    $begingroup$
    @L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
    $endgroup$
    – Gumby The Green
    May 26 at 4:10







  • 1




    $begingroup$
    I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
    $endgroup$
    – Yet Another User
    May 26 at 6:12






  • 3




    $begingroup$
    @CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
    $endgroup$
    – Gumby The Green
    May 26 at 10:38







  • 1




    $begingroup$
    Note that the expression (high + low) may overflow.
    $endgroup$
    – Carsten S
    May 26 at 13:26







3




3




$begingroup$
I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
$endgroup$
– L. F.
May 26 at 3:20




$begingroup$
I’m afraid I have to differ on bit shifting instead of division. This is not necessarily faster, and it reduces readability significantly. See stackoverflow.com/q/6357038/9716597.
$endgroup$
– L. F.
May 26 at 3:20




1




1




$begingroup$
@L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
$endgroup$
– Gumby The Green
May 26 at 4:10





$begingroup$
@L.F., I just de-emphasized that part and added a comment to help the readability of the bit shift. It very well might not help but it's easy enough to test. If this is performance critical, which I assume it is (why use a binary search otherwise?), it's worth testing, IMO, since the division is happening in a loop within a loop.
$endgroup$
– Gumby The Green
May 26 at 4:10





1




1




$begingroup$
I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
$endgroup$
– Yet Another User
May 26 at 6:12




$begingroup$
I will eat my hat if you put the division by 2 into godbolt.org and don't get exactly the same assembly as a bit shift with -O2.
$endgroup$
– Yet Another User
May 26 at 6:12




3




3




$begingroup$
@CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
$endgroup$
– Gumby The Green
May 26 at 10:38





$begingroup$
@CarstenS, in this case, the dev has info that the compiler might not - that the dividend is always non-negative - so communicating that to the compiler somehow can help it optimize. It looks like simply appending a u to the 2 in the OP's code also works, so that's probably the most readable way to do it. I'll add it to the answer.
$endgroup$
– Gumby The Green
May 26 at 10:38





1




1




$begingroup$
Note that the expression (high + low) may overflow.
$endgroup$
– Carsten S
May 26 at 13:26




$begingroup$
Note that the expression (high + low) may overflow.
$endgroup$
– Carsten S
May 26 at 13:26

















draft saved

draft discarded
















































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.




draft saved


draft discarded














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





















































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







Popular posts from this blog

Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020