Jump to content

[C++] Cautare binara / Binary Search


AIM RaJa
 Share

Recommended Posts

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;
        }
    }
}
Link to comment
Share on other sites

Cred c-ar fi fost mai bine sa folosesti asa ceva pentru structura, ca sa o poti folosi pentru orice tip de data

template < typename type > struct element{
    type element;
    UINT ordin; //Unsigned int
};

In rest, imi place tutorialul. Cred c-o sa fac si la scoala asa ceva anu' asta.

Edited by Cdorsu
Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.