Saturday, June 8, 2013

Binary Search in Java

First thing that we must keep in mind when applying binary search is that it works only on sorted lists. In this search technique, we begin our search from the middle element on the list. 
If the key is found, we stop our search, otherwise, if the key is less than the middle element, the process is repeated in the left half of the list, otherwise, if the key is greater than the middle element, then the process is repeated in the right half of the list.
Below is the code written in Java that implements Binary Search in a one-dimensional array:
import java.io.*;
class BinarySearch{

public static void main(String args[])throws IOException{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader (isr);
int a[]={7, 10, 12, 34, 45,51, 60, 78, 81, 92};
int key, low=0, high=a.length-1, mid=0;
System.out.print("Enter the integer to search:");        key=Integer.parseInt(br.readLine());
while(low<=high){
mid=(low+high)/2;
if (key==a[mid])
break;
else if(key<a[mid])
high=mid-1;
else
low=mid+1;
}
if(low<=high)
System.out.println(key+" found at index "+mid);
else
System.out.println(key+" not found");
}
}
Binary Search is considered to be much faster than Linear Search, as the size of the input (list) grows.

5 comments:

  1. www.diversionsandreality.blogspot.com

    ReplyDelete
  2. https://diversionsandreality.blogspot.com

    ReplyDelete
  3. I came on the Internet i saw great testimony about DR Voke on how he was able to cure someone from HERPES, and any disease this person said great things about this man, and advice we contact him for any problem that DR Voke can be of help, well i decided to give him a try, he requested for my information which i sent to him, and he told me he was going to prepare for me a healing portion, which he wanted me to take for days, and after which i should go back to the hospital for check up, well after taking all the treatment sent to me by DR Voke i went back to the Hospital for check up, and now i have been confirmed HERPES Negative, friends you can reach Dr voke on any treatment for any Disease, reach him on _________________________________[doctorvoke@yahoo.com]

    ReplyDelete