Menú

Simple binary search

Simple binary search - student project

A simple binary search algorithm that looks for the desired value and returns its index. If that value shall not be found, it returns -1.

#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> A(10);
int binarysearch(int value) {
int low = 0;
int medium = 0;
int high = A.size() - 1;
while (low <= high) {
medium = (high - low) / 2 + low;
if (A[medium] < value) {
low = medium + 1;
} else if (A[medium] > value) {
high = medium - 1;
} else {
return medium;
}
}
return -1;
}

int main() {

srand(time(NULL));
for (int i = 0; i < A.size(); i++) {
A[i] = rand() % 10 + 1;
}
sort(A.begin(), A.end());
for (int i = 0; i < A.size(); i++) {
cout << A[i] << "\t";
}
int k = 0;
cout << endl << "Insert the value you wish to search for: ";
cin >> k;
cout << endl << "Here is the index of your value: " << binarysearch(k);
}