Binary Search in C++17





.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

136k21 gold badges175 silver badges445 bronze badges




136k21 gold badges175 silver badges445 bronze badges










asked May 25 at 14:41









greggreg

5643 silver badges11 bronze badges




5643 silver badges11 bronze badges











  • 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


















15














$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





















8














$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/4.0/"u003ecc by-sa 4.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









15














$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


















15














$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
















15














15










15







$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

13.4k20 silver badges55 bronze badges




13.4k20 silver badges55 bronze badges










answered May 25 at 16:34









vnpvnp

43.3k2 gold badges36 silver badges110 bronze badges




43.3k2 gold badges36 silver badges110 bronze badges















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















8














$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


















8














$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
















8














8










8







$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,1173 gold badges12 silver badges38 bronze badges




4,1173 gold badges12 silver badges38 bronze badges















  • $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 bronze badges




413 bronze badges











  • 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

Færeyskur hestur Heimild | Tengill | Tilvísanir | LeiðsagnarvalRossið - síða um færeyska hrossið á færeyskuGott ár hjá færeyska hestinum

He _____ here since 1970 . Answer needed [closed]What does “since he was so high” mean?Meaning of “catch birds for”?How do I ensure “since” takes the meaning I want?“Who cares here” meaningWhat does “right round toward” mean?the time tense (had now been detected)What does the phrase “ring around the roses” mean here?Correct usage of “visited upon”Meaning of “foiled rail sabotage bid”It was the third time I had gone to Rome or It is the third time I had been to Rome

Slayer Innehåll Historia | Stil, komposition och lyrik | Bandets betydelse och framgångar | Sidoprojekt och samarbeten | Kontroverser | Medlemmar | Utmärkelser och nomineringar | Turnéer och festivaler | Diskografi | Referenser | Externa länkar | Navigeringsmenywww.slayer.net”Metal Massacre vol. 1””Metal Massacre vol. 3””Metal Massacre Volume III””Show No Mercy””Haunting the Chapel””Live Undead””Hell Awaits””Reign in Blood””Reign in Blood””Gold & Platinum – Reign in Blood””Golden Gods Awards Winners”originalet”Kerrang! Hall Of Fame””Slayer Looks Back On 37-Year Career In New Video Series: Part Two””South of Heaven””Gold & Platinum – South of Heaven””Seasons in the Abyss””Gold & Platinum - Seasons in the Abyss””Divine Intervention””Divine Intervention - Release group by Slayer””Gold & Platinum - Divine Intervention””Live Intrusion””Undisputed Attitude””Abolish Government/Superficial Love””Release “Slatanic Slaughter: A Tribute to Slayer” by Various Artists””Diabolus in Musica””Soundtrack to the Apocalypse””God Hates Us All””Systematic - Relationships””War at the Warfield””Gold & Platinum - War at the Warfield””Soundtrack to the Apocalypse””Gold & Platinum - Still Reigning””Metallica, Slayer, Iron Mauden Among Winners At Metal Hammer Awards””Eternal Pyre””Eternal Pyre - Slayer release group””Eternal Pyre””Metal Storm Awards 2006””Kerrang! Hall Of Fame””Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Bullet-For My Valentine booed at Metal Hammer Golden Gods Awards””Unholy Aliance””The End Of Slayer?””Slayer: We Could Thrash Out Two More Albums If We're Fast Enough...””'The Unholy Alliance: Chapter III' UK Dates Added”originalet”Megadeth And Slayer To Co-Headline 'Canadian Carnage' Trek”originalet”World Painted Blood””Release “World Painted Blood” by Slayer””Metallica Heading To Cinemas””Slayer, Megadeth To Join Forces For 'European Carnage' Tour - Dec. 18, 2010”originalet”Slayer's Hanneman Contracts Acute Infection; Band To Bring In Guest Guitarist””Cannibal Corpse's Pat O'Brien Will Step In As Slayer's Guest Guitarist”originalet”Slayer’s Jeff Hanneman Dead at 49””Dave Lombardo Says He Made Only $67,000 In 2011 While Touring With Slayer””Slayer: We Do Not Agree With Dave Lombardo's Substance Or Timeline Of Events””Slayer Welcomes Drummer Paul Bostaph Back To The Fold””Slayer Hope to Unveil Never-Before-Heard Jeff Hanneman Material on Next Album””Slayer Debut New Song 'Implode' During Surprise Golden Gods Appearance””Release group Repentless by Slayer””Repentless - Slayer - Credits””Slayer””Metal Storm Awards 2015””Slayer - to release comic book "Repentless #1"””Slayer To Release 'Repentless' 6.66" Vinyl Box Set””BREAKING NEWS: Slayer Announce Farewell Tour””Slayer Recruit Lamb of God, Anthrax, Behemoth + Testament for Final Tour””Slayer lägger ner efter 37 år””Slayer Announces Second North American Leg Of 'Final' Tour””Final World Tour””Slayer Announces Final European Tour With Lamb of God, Anthrax And Obituary””Slayer To Tour Europe With Lamb of God, Anthrax And Obituary””Slayer To Play 'Last French Show Ever' At Next Year's Hellfst””Slayer's Final World Tour Will Extend Into 2019””Death Angel's Rob Cavestany On Slayer's 'Farewell' Tour: 'Some Of Us Could See This Coming'””Testament Has No Plans To Retire Anytime Soon, Says Chuck Billy””Anthrax's Scott Ian On Slayer's 'Farewell' Tour Plans: 'I Was Surprised And I Wasn't Surprised'””Slayer””Slayer's Morbid Schlock””Review/Rock; For Slayer, the Mania Is the Message””Slayer - Biography””Slayer - Reign In Blood”originalet”Dave Lombardo””An exclusive oral history of Slayer”originalet”Exclusive! Interview With Slayer Guitarist Jeff Hanneman”originalet”Thinking Out Loud: Slayer's Kerry King on hair metal, Satan and being polite””Slayer Lyrics””Slayer - Biography””Most influential artists for extreme metal music””Slayer - Reign in Blood””Slayer guitarist Jeff Hanneman dies aged 49””Slatanic Slaughter: A Tribute to Slayer””Gateway to Hell: A Tribute to Slayer””Covered In Blood””Slayer: The Origins of Thrash in San Francisco, CA.””Why They Rule - #6 Slayer”originalet”Guitar World's 100 Greatest Heavy Metal Guitarists Of All Time”originalet”The fans have spoken: Slayer comes out on top in readers' polls”originalet”Tribute to Jeff Hanneman (1964-2013)””Lamb Of God Frontman: We Sound Like A Slayer Rip-Off””BEHEMOTH Frontman Pays Tribute To SLAYER's JEFF HANNEMAN””Slayer, Hatebreed Doing Double Duty On This Year's Ozzfest””System of a Down””Lacuna Coil’s Andrea Ferro Talks Influences, Skateboarding, Band Origins + More””Slayer - Reign in Blood””Into The Lungs of Hell””Slayer rules - en utställning om fans””Slayer and Their Fans Slashed Through a No-Holds-Barred Night at Gas Monkey””Home””Slayer””Gold & Platinum - The Big 4 Live from Sofia, Bulgaria””Exclusive! Interview With Slayer Guitarist Kerry King””2008-02-23: Wiltern, Los Angeles, CA, USA””Slayer's Kerry King To Perform With Megadeth Tonight! - Oct. 21, 2010”originalet”Dave Lombardo - Biography”Slayer Case DismissedArkiveradUltimate Classic Rock: Slayer guitarist Jeff Hanneman dead at 49.”Slayer: "We could never do any thing like Some Kind Of Monster..."””Cannibal Corpse'S Pat O'Brien Will Step In As Slayer'S Guest Guitarist | The Official Slayer Site”originalet”Slayer Wins 'Best Metal' Grammy Award””Slayer Guitarist Jeff Hanneman Dies””Kerrang! Awards 2006 Blog: Kerrang! Hall Of Fame””Kerrang! Awards 2013: Kerrang! Legend”originalet”Metallica, Slayer, Iron Maien Among Winners At Metal Hammer Awards””Metal Hammer Golden Gods Awards””Bullet For My Valentine Booed At Metal Hammer Golden Gods Awards””Metal Storm Awards 2006””Metal Storm Awards 2015””Slayer's Concert History””Slayer - Relationships””Slayer - Releases”Slayers officiella webbplatsSlayer på MusicBrainzOfficiell webbplatsSlayerSlayerr1373445760000 0001 1540 47353068615-5086262726cb13906545x(data)6033143kn20030215029