0

I have a class in which a binary search is implemented.

import java.util.Arrays;
import java.util.Random;

public class BinarySearch {

   public static boolean search(int[] array, int value) {
       int left = 0;
       int right = array.length - 1;
        while (left <= right) {
           int index = (right + left) / 2;
           if (array[index] == value)
               return true;
           if (array[index] < value)
               right = index - 1;
           else
               left = index + 1;
       }
       return false;

   }

   public static void main(String[] arg) {
       int[] array = {1,2,3,4,5,6,7,8};
       int value = 4 ;

       if (search(array,value))
           System.out.println("The value " + value + " is in the array.");
       else {
           System.out.println("The value " + value + " is not in the array.");
       }
   }
}

The problem is, when I replace the value of 4 in the main method, it will always print out e.g. The value 8 is not in the array. However, I can't find the bug in the search method. Can anybody of you see it? I tried using a debugger, but it still doesn't help me.

NewbieJava
  • 133
  • 11
  • Welcome to Stack Overflow! [What does your step debugger tell you?](http://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) –  Nov 13 '17 at 10:42
  • Make the following changes to your code. if (array[index] == value) return true; if (array[index] < value) left = index + 1; else right = index - 1; When element searched for > element[index], we need to shift the search towards right. when element searched for < element[index], we need to search for left – akshaya pandey Nov 13 '17 at 10:45
  • Basically your logic is not correct, it should be `array[index] < value then left = index + 1 else right = index`. Try to use debugging method then you come to know. – sayboras Nov 13 '17 at 10:46
  • 1
    Change `if (array[index] < value)` to `if (array[index] > value)` – Jesper Nov 13 '17 at 10:46
  • Ahh so that was it. Thanks!! – NewbieJava Nov 13 '17 at 10:48

0 Answers0