D
D
daniel12014-05-10 13:47:03
C++ / C#
daniel1, 2014-05-10 13:47:03

Why doesn't binary search work?

Hello, I have a problem - binary search is not working. And to be more precise, it does not work with all values. If you look for the number 6, for example, then the program goes into an endless loop.

static void Main(string[] args)
        {
            int[] A = { 1, 3, 5, 6, 8, 9, 10, 24, 100, 156 };
          
            
            Console.WriteLine(BinarySearch(A, A.Length, 6));
            Console.Read();
        }
        
        static int BinarySearch(int[] A,int n,int x)
        {
            int p = 1;
            int r = n;
            while(p<=r)
            {
                int q = (p + r) / 2;
                if(A[q]==x)
                {
                    return q;
                }
                if(A[q]>x)
                {
                    r = q - 1;
                }
                if(A[q]<x)
                {
                    r = q + 1;
                }
            }
            return -1;
        }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Vershinin, 2014-05-10
@WolfdalE

He's kind of weird.
Correct like this:

static int BinarySearch(int[] A, int n, int x)
{	
  int left_bound = 0, right_bound = n, q;

  while(left_bound != right_bound)
  {
    q = (left_bound + right_bound) >> 1;
    
    if(A[q] == x)
        return q;
    else if(A[q] > x)
        right_bound = q;
    else
        left_bound = q;
  }

  return -1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question