Binary Search Java Program

Binary Search is a searching algorithm which takes less time than linear searching, due to the fact that binary search divides the well arranged sorted elements into two parts and then further checks whether the element which need to be searched comes under lower part that is less or comes under upper part. that's why the binary search algorithm executes in O(log N) time.
The source code for binary search program in Java programming language is given below with the output :

Java Program Source Code of Binary Search

import java.util.*;
public class BinarySearch
{
  public static void main(String[] args)
{
       int[] intArray = new int[10];
       int searchValue = 0, index;
       System.out.println("Enter 10 numbers");
       Scanner input = new Scanner(System.in);
       for (int i = 0; i<intArray.length; i++)
       {
               intArray[i] = input.nextInt();
       }
       System.out.print("Enter a number to search for: ");
       searchValue = input.nextInt();
       index = binarySearch(intArray, searchValue);
       if (index != -1)
       {
               System.out.println("Found at index: " + index);
       }
       else
       {
               System.out.println("Not Found");
       }
  }
           static int binarySearch(int[] search, int find)
           {
           int start, end, midPt;
           start = 0;
           end = search.length - 1;
           while (start <= end)
           {
                   midPt = (start + end) / 2;
                   if (search[midPt] == find)
                   {
                           return midPt;
                   }
                    else if (search[midPt] < find)
                    {
                           start = midPt + 1;
                    }
                   else
                    {
                           end = midPt - 1;
                    }
           }
                    return -1;
           }
}

Output of Java Program Source Code of Binary Searching

0 comments:

Post a Comment