binary_search in c++ unexpected behaviour

前端 未结 4 823
暖寄归人
暖寄归人 2021-01-25 13:41

The following snippet is returning me 0. I expected it to be 1. What\'s wrong going on here?

#include 
#include 
#include 

        
4条回答
  •  再見小時候
    2021-01-25 14:38

    I ran the program and saw this:

    11
    22
    10
    20
    30
    40
    50
    
    Binary Search -  0
    

    Your array is not sorted, therefore, binary search fails. (it sees 11 in the first position, and concludes 10 does not exist here)

    You either want to ensure the array is sorted before binary searching or use the regular std::find.

提交回复
热议问题