I am trying to carry out a binary search to find the index of a specific element within the vector. I tried getting the first and last element and passing them to the variable high and low. I am getting some sort of conversion error. The error is below inside the BinarySearchVector funtion.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int limit=10;
vector <int> elements;
void AddValueToVector(){
cout<<"Hello World:"<<endl;
for (int i = 0; i < limit; i )
{
int a;
cin>>a;
elements.push_back(a);
}
}
void printContents(){
cout<<"Vector elements:"<<endl;
for (int j = 0; j < limit; j )
{
cout<<elements[j]<<endl;
}
}
int binarySearchVector(vector<int>&elements,int searchval){
sort(elements.begin(),elements.end());
auto low= elements.begin();
auto high= elements.end();
while (low <= high) {
int mid = low (high - low) / 2;
if (elements[mid] == searchval)
return mid;
if (elements[mid] < searchval)
low = mid 1;
else
high = mid - 1;
}
return -1;
}
void search(){
int searchval;
cout<<"Enter value to search:"<<endl;
cin>>searchval;
int result= binarySearchVector(elements,searchval);
if (result==-1)
{
cout<<"Not Found"<<endl;
}else{
cout<<"Element is found at index"<<result<<endl;
}
}
int main()
{
AddValueToVector();
printContents();
search();
return 0;
}
Any recommendations will be greatly appreciated.
CodePudding user response:
To use the binary search method you need to sort the vector.
The variables low and high are iterators
auto low= elements.begin();
auto high= elements.end();
There is no implicit conversion an iterator to an object of the type int that you are trying to do
while (low <= high) {
int mid = low (high - low) / 2;
//...
You need to write at least
auto mid = low (high - low) / 2;
or
auto mid = std::next( low, std::distance( low, high ) / 2 );
Moreover the condition in the loop
while (low <= high) {
is incorrect for an empty vector. You need to write
while (low < high) {
CodePudding user response:
You mean
int mid = *low (*high - *low) / 2;
an iterator is effectively a pointer to the element. If you want the element itself you need to dereference it
CodePudding user response:
Since your binarySearchVector
function is supposed to return the index of the found element (not an iterator) you should probably not use begin()
and end()
(that return iterators, not indices).
Example:
int binarySearchVector(std::vector<int>& elements, int searchval) {
std::sort(elements.begin(), elements.end());
int low = 0; // index of first element
int high = elements.size() - 1; // index of last element
while (low <= high) {
int mid = low (high - low) / 2;
if (elements[mid] < searchval)
low = mid 1;
else if (elements[mid] > searchval)
high = mid - 1;
else
return mid;
}
return -1;
}