arrays - Binary Search gives Index Out of Bound Exception in Java -


i trying implement binary search using java programming language. it's obvious array should sorted in order make use of binary search because uses divide , conquer concept. code works fine both cases when when element within array , when it's not. but, when enter number greater greatest number inside array, program crash , give index out of bound exception.

public class binary {  public static void search(int arr[]) {     scanner in = new scanner(system.in);     int upper = arr.length;     int lower = 0;     int middle = 0;     int flag = 0;     int key;      /*      * flag = 0 ---> not found yet.      * flag = 1 ---> element found.      * flag = 2 ---> no such element.      */      system.out.println("enter number want find... ");     key = in.nextint();      while (flag == 0) {         middle = (int) (lower + upper) / 2;          if (key == arr[middle]) {             flag = 1;         }          if (key < arr[middle]) {             upper = middle - 1;         } else if (key > arr[middle]) {             lower = middle + 1;         }         if (lower > upper) {             flag = 2;         }     }     if (flag == 1) {         system.out.println(arr[middle] + " has been found, index is: "                 + middle);     } else         system.out.println("error, no such element."); }  public static void main(string[] args) {      int arr[] = { 2, 4, 6, 8, 11, 34, 56 };     search(arr); } 

}

this should solve problem

int upper = arr.length-1; 

if looking number greater greatest, sure @ last element of array. in code upper has initial value 1 more index of last element.


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -