public class BinarySearch {

* arrayBinarySearch
* job of this method
* define while loop
* check on three possible answers
* first if  key less than midlle number of array
* perform high equal mid-1
* else if key equal mid number then it retrun mid number
* third condition if key larger than middle number
* then  make low = mid+1
* else out of condition

private static int arrayBinarySearch(int array[],int keyForSearch){

int low=0;
int high=array.length-1;

int mid=(low+high)/2;


else if(keyForSearch==array[mid])
return mid;

// if key large than middle number

return -low-1;
//no high < low

}//end of method

public static void main(String []args){
//create  an object to call method
BinarySearch objectToCallMethod =new BinarySearch();
//array to test method  mid=8
int arrayForTestMethod[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};

// less than mid   high=mid-1   low=0
System.out.println( objectToCallMethod.arrayBinarySearch(arrayForTestMethod, 5));
//equal mid return mid

System.out.println( objectToCallMethod.arrayBinarySearch(arrayForTestMethod, 8));

//large than mid  low=mid+1  high=array.length
System.out.println( objectToCallMethod.arrayBinarySearch(arrayForTestMethod, 14));

}//end of main

}//end of class


One thought on “BinarySearch

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s