binary search algorithm code example
Example: binary search
//Binary search can apply to sorted data only.
//Time complexity of binary search is O(log n ).
//It always divide the whole data in parts and compare a search key to middle element only.
import java.util.*;
public class BinarySearch {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
int[] a = {10,20,50,30,40};
int key=sc.nextInt();
Arrays.sort(a); // An method in java.util.Arrays package to sort an array element.
int first=0,end=a.length-1,mid=0,flag=0;
while(first<=end)
{
mid=(first+end)/2;
if(key<a[mid]) // Move to left part if key is smaller than middle element.
{
end = mid-1;
}
else if(key>a[mid]) // Move to right part if key is greater than middle element.
{
first = mid+1;
}
else
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("Success! found");
}
else
{
System.out.println("Error! This key (" + key + ") does not exist in the array");
}
}
}