Ad

Sunday, 8 February 2015

To implement Binary Search algorithm in Java

Below program sample will show how to search for a particular element in the array using binary search.Make sure the array is sorted before we use the binary search.Binary search algorithm is very fast when compared to linear search(where each element in the array is checked).
Binary Search algorithm is pretty simple:
  • First it will check the middle element of the array.
  • If it is smaller than the search element,then the first part of the array is considered for the further search(leaving behind the second part),
  • Else the second part of the array is considered for the further search.
  • The above logic is continued until we find the search element or the start index of the filtered array is not greater than end index(where the element is not found)
public class BinarySearchSample {                                                                                                      

public static void main(String[] args) {

int [] arry= new int[]{3,5,9,13,25,40,55,90,121,150};
        int low=0;
        if(args.length==0)
        {
        System.out.println("Please pass the element to search in the array");
        }
        int src=Integer.parseInt(args[0]);//element to Search for
        int mid=0;
        int high=arry.length-1;
        boolean isFound=false;
        while(low<=high)
        {
        mid=(low+high)/2;
        System.out.println("low:"+low+" mid:"+mid+" high:"+high);
        if(src<arry[mid])
        {
        high=mid-1;
        }
        else if(src > arry[mid])
        {
        low=mid+1;
        }
        else
        {
        isFound=true;
        break;
        }        
        }
if(isFound)
{
System.out.println("Found "+src+" at index:"+mid);
}
else
{
System.out.println(src+" not found");
}
}
}

Output:

When you run the above program by passing the argument as 150(element to search for),we will get the below output

low:0 mid:4 high:9                                                                                                                                  
low:5 mid:7 high:9
low:8 mid:8 high:9
low:9 mid:9 high:9
Found 150 at index:9

If we analyse the above output,binary search took only 4 iterations to find the last element in the array,whereas in linear search it will take 10 iterations to find the same element in the above array.

No comments:

Post a Comment