binary search algorithm for cpp code example
Example 1: binary search program c++
#include <iostream>
using namespace std;
int binarySearch(int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
int main ()
{
const int size = 5;
int array[size] = {1, 2, 3, 4, 5};
int value;
int result;
cout << "What value would you like to search for? ";
cin >> value;
result = binarySearch(array, size, value);
if (result == -1)
cout << "Not found\n";
else
cout << "Your value is in the array.\n";
return 0;
}
Example 2: c++ binary search
#include <algorithm>
#include <vector>
bool binarySearchVector(const std::vector<int>& vector,
int target) {
return std::binary_search(vector.cbegin(), vector.cend(), target);
}
#include <iostream>
int main()
{
std::vector<int> haystack {1, 3, 4, 5, 9};
std::vector<int> needles {1, 2, 3};
for (auto needle : needles) {
std::cout << "Searching for " << needle << std::endl;
if (binarySearchVector(haystack, needle)) {
std::cout << "Found " << needle << std::endl;
} else {
std::cout << "no dice!" << std::endl;
}
}
}