c++ - Locate an element in unsorted vector by using binary search on sorted vector -
i have been trying position of element in vector using binary search only, no loops, nothing, binary search functions library algorithm
.
since binary search functions work on sorted container types, not know how position of searched element of original vector, since in once vector sorted, position of searched element not same in original vector.
i made code work std::find
main goal binary search functions only.
code:
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v {1, 10, 100, -11, -112, -17, 44, -99, 99, 558}; std::vector<int> sorted = v; std::sort(sorted.begin(), sorted.end()); std::cout << "enter number: "; int number; std::cin >> number; if(std::binary_search(sorted.begin(), sorted.end(), number) == false) { std::cout << "there no entered number."; } else { std::cout << "number located on position: "; std::cout << std::find(v.begin(), v.end(), number) - v.begin(); } return 0; }
example of output:
1°
enter number: 99 number located on position: 8
2°
enter number: -546 there no entered number.
so if me make work binary functions , not std::find
or give me few ideas, grateful.
thanks :)
if want binary search , have result refer original unsorted array -- need index sort , search -- instead of sorting , searching on copy of array, operate on array of indexes original array. like:
std::vector<int> v {1, 10, 100, -11, -112, -17, 44, -99, 99, 558}; std::vector<int> sort_indexes(v.size()); (size_t = 0; < v.size(); ++i) sort_indexes[i] = i; std::sort(sort_indexes.begin(), sort_indexes.end(), [&v](int a, int b)->bool { return v[a] < v[b]; }); std::cout << "enter number: "; int number; std::cin >> number; auto found = std::lower_bound(sort_indexes.begin(), sort_indexes.end(), number, [&v](int a, int b)->bool { return v[a] < b; } ); if (found == sort_indexes.end() || v[*found] > number) { std::cout << "there no entered number." << std::endl; } else { std::cout << "number located on position: " << *found << std::endl; }
Comments
Post a Comment