Can we apply binary search on c++ list and vector? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can we apply binary search on c++ list and vector?

Binary search algorithm on c++ list and vector. How can we do that? is there any restrictions? please help.

21st May 2018, 8:54 AM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
5 Answers
+ 3
It seems the built-in binary_search function in <algorithm> works on lists. Thus, you may declare a similar binary_search function based on the one from <algorithm> You can find details on it here : www.cplusplus.com/reference/algorithm/binary_search en.cppreference.com/w/cpp/algorithm/binary_search https://code.sololearn.com/cGvcTDlqNa6s/?ref=app
21st May 2018, 1:02 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 8
I'm fairly sure that unlike vector, list does not provide random access, which means that you have to iterate through the list to get an item. vec[5] // sixth element list[5] // nope This means that you can apply binary search on vector, given that the vector is sorted. https://www.sololearn.com/learn/683/?ref=app https://www.sololearn.com/learn/261/?ref=app
21st May 2018, 9:59 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
Aha, there's the catch. https://stackoverflow.com/questions/14320395/binary-search-in-a-sorted-list-with-all-nodes-as-struct-c It "works", but doesn't really carry out binary search on std::list the way you would expect it to. Nonetheless, interesting discovery. Kinshuk Vasisht
21st May 2018, 2:04 PM
Hatsy Rei
Hatsy Rei - avatar
+ 3
Hatsy Rei Thank you!!!
21st May 2018, 10:16 AM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar
+ 2
21st May 2018, 1:23 PM
$ยข๐Žโ‚น๐”ญ!๐จ๐“
$ยข๐Žโ‚น๐”ญ!๐จ๐“ - avatar