Write a program on Binary Search in java?

Introduction:

Hii all, here we are going understand the most interesting and frequently asked code in any of the language.As from the topic only we can predict the advantage of this code.Binary search is used to search the required element in the sorted array. Sorted array means the array should be in ascending order or in descending order, for binary search we are taking an array of ascending order elements.

Description Of Program:

First of all, we will take an array and input a scanner function so that user can insert the required value.In the given code “n” is taken as a required input number, then we will check for the conditions in “while(true)” keyword if the data will match the inserted data then it will return the value.”l” is 0th element in the array and “r” is the last element in the array. The strategy to search the element is first to check the element in the middle position if luckily we will get the inserted data at the middle position then the program will return to that position only if we don’t get the data at the middle position then we will check whether the data inserted is greater than the a[mid] if yes then the left position will shifted to mid+1 and else right position will be shifted to mid-1.Again it may be the inserted data will not match any element in the given array then we will print “Not Found”.Hope you find it helpful.

Thank You!

CODE :

package arrays;

import java.util.Scanner;
public class BinarySearch {
public static void main(String[] args) {

int a[]={1,3,4,5,6,7,8,9};
int l=0,r=a.length-1;
System.out.println(“Enter the required value”);
Scanner s=new Scanner(System.in);
int n=s.nextInt();
while(true)
{
int mid=(l+r)/2;
System.out.printf(“l=%s, mid =%s, r=%s\n”,l,mid,r);
if(n==a[mid]){
System.out.println(“Found at ” + mid);
return;
}
if(n>a[mid])
l=mid+1;
else
r=mid-1;
if(l>r)
{
System.out.println(“Not Found”);
return;
}
}
}
}

OUTPUT :

Leave a Reply