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

Wikipedia:Vital articles Мазмуну Biography - Өмүр баян Philosophy and psychology - Философия жана психология Religion - Дин Social sciences - Коомдук илимдер Language and literature - Тил жана адабият Science - Илим Technology - Технология Arts and recreation - Искусство жана эс алуу History and geography - Тарых жана география Навигация менюсу

Bruxelas-Capital Índice Historia | Composición | Situación lingüística | Clima | Cidades irmandadas | Notas | Véxase tamén | Menú de navegacióneO uso das linguas en Bruxelas e a situación do neerlandés"Rexión de Bruxelas Capital"o orixinalSitio da rexiónPáxina de Bruselas no sitio da Oficina de Promoción Turística de Valonia e BruxelasMapa Interactivo da Rexión de Bruxelas-CapitaleeWorldCat332144929079854441105155190212ID28008674080552-90000 0001 0666 3698n94104302ID540940339365017018237

What should I write in an apology letter, since I have decided not to join a company after accepting an offer letterShould I keep looking after accepting a job offer?What should I do when I've been verbally told I would get an offer letter, but still haven't gotten one after 4 weeks?Do I accept an offer from a company that I am not likely to join?New job hasn't confirmed starting date and I want to give current employer as much notice as possibleHow should I address my manager in my resignation letter?HR delayed background verification, now jobless as resignedNo email communication after accepting a formal written offer. How should I phrase the call?What should I do if after receiving a verbal offer letter I am informed that my written job offer is put on hold due to some internal issues?Should I inform the current employer that I am about to resign within 1-2 weeks since I have signed the offer letter and waiting for visa?What company will do, if I send their offer letter to another company