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

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

Bunad

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