Frage

I have only included the function. I am trying to implement binary search but for some reason it is not working. What I am really trying to determine is whether the algorithm is correct. It appears fine to me....but may be I am wrong. I know that the algorithm has to be sorted first but that will be taken care of in another function. Is the algorithm wrong or right? For some unknown reason the programme hangs...I have taken care of all the headers etc....i am off target or what? Thanks. Function is in C.

bool search(int value, int values[], int n)
{
    int i;
    int begin = 0;
    int end = n-1;
    int middle = (begin + end)/2;

    for ( i = 0; middle <=end; i++)
        if (value == values[middle])
        {
            return true; 
            break;
        }
        else if (value > values[middle])
        {
            begin = values[middle +1];
        }
        else 
        {
            end = values[middle -1];
        }
    return false;
}
War es hilfreich?

Lösung

You do not need the loop on i.

Your loop would be on begin and end, such as while( begin < end )

Depending on how values[middle] compare with values[begin] and values[end], you have to adjust begin (begin = middle + 1;) or end (end = middle - 1;). Beware of the boundary cases!

Andere Tipps

(begin + end) / 2 may caused integer overflow in C. Try to use begin + (end - begin) / 2 instead.

What is the algorithm you have in mind ? I would suggest to go through the algorithm first . http://en.wikipedia.org/wiki/Binary_search

Your middle is calculating to the end. It should be middle = (end - begin) / 2

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top