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 Respuestas
+ 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
Solo Wanderer 4315
Solo Wanderer 4315 - 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