Cautare binara - Varianta clasica
#include <iostream>
#include <algorithm>
using namespace std;
int N, x;
struct element {
int val, ord;
} V[100];
int bin_search(int b, int e, int x);
bool cmp(element a, element b) {
return a.val < b.val;
}
int main() {
cout << "N = ";cin >> N;
for(int i = 1; i <= N; ++i) {
cout << "V[" << i << "] = ";cin >> V[i].val;
V[i].ord = i;
}
sort(V + 1, V + 1 + N, cmp);
cout << "x = ";cin >> x;
cout << V[bin_search(1, N, x)].ord << '\n';
return 0;
}
int bin_search(int b, int e, int x) {
if(b > e) {
return 0;
}
int mij = (b + e) / 2;
if(V[mij].val > x) {
return bin_search(b, mij - 1, x);
}
else {
if(V[mij].val < x) {
return bin_search(mij + 1, e, x);
}
else {
return mij;
}
}
}