/BinarySearch

BinarySearch

Binary Search is used to find an element in an array of element in logarithmic time. The time complexity of Binary Search is O(log n).Which is very fast in comparision to linear search.

Features

  • Binary Search works for only sorted array.
  • Binary Search is very fast it find the element in log n time.
  • In Binary Search we first find the middle of the sorted array by adding first and last index and then dividing it by 2.
  • if theĀ  element in the middle index is the required element then we return the middle index position.
  • else we check wheather the element in the middle index is greater than the required element then we search in the left hand side.
  • else we check on the right hand side of the array.

 

Example

 

public class BinarySearch {
public static void main(String args[])
{
int a[]={10,15,17,18,20,23,32,35};
int element=18;
int start=0;
int last=a.length-1;
int middle=(start+last)/2;

while(start<=last)
{
if(a[middle]==element)
{
System.out.println("Element Found At "+(middle+1));
return;
}
else if(a[middle]>element)
{
last=middle-1;
}
else if(a[middle]<element)
{
start=middle+1;
}
middle=(start+last)/2;
}
System.out.println("Element Not Found");
}
}