简体   繁体   中英

C++ binary search struggle

Sorry for using polish names but I started with them and didin't want to confuse myself. I've got an assignment to find the possible answer to this equation x^3 + px = q , without negative numbers. Also I Have to use binary searching for that, it seemed to me pretty easy at first but I keep on getting wrong outputs. Just wanted some advice on what I should focus on, not an entire solution. Cheers!

int main() {
int p, q, x;
cin >> p >> q;
int tablica[q-1];
for(int i = q-1; i>=0; i--){
    tablica[i] = q;
    q--;
}
bool znalezione = false;
int poczatek = 0;
int koniec = q-1;


while(!znalezione){
    int srodek = (poczatek + koniec)/2;
    tablica[srodek] = x;
    if(x*x*x + p*x == q){
        znalezione = true;
    }
    else
        if(x*x*x + p*x > q){
            koniec = srodek -1;
        }
        else
            poczatek = srodek +1;
}
cout << x;

}

You are trying to find the value of x . The first thing that I notice is that x is not initialized and then in the line tablica[srodek] = x , you are assigning this to array, this will give a garbage value in tablica .

Additionally, you are never updating the value of x . It will always display the value which was at the beginning (garbage value in your case)

int tablica[q-1]; is not standard c++, use std::vector . I'm not sure why you even need a table. You've got the general idea but you never assigned anything to x . Binary search algorithm is something like this:

std::optional<int> binary_search(int begin, int end, int element)
{
    while(end-begin>0)
    {
        int midPoint = (end+begin)/2;
        if(midPoint ==element)
            return midPoint;
        else if (midPoint > element)
            begin = midPoint+1;
        else
            end = midPoint-1;
    }
    return {};
}

So all you have to do is replace insides of those if statements with your equation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM