Explain Binary Search in Java. Also write a program using for loop, giving examples.

Binary Search in Java

Binary search is used to search a key element from multiple elements. Binary search is faster than a linear search.
In the case of binary search, array elements must be in ascending order. If you have an unsorted array, you can sort the array using Arrays sorting a[] method.

Example Of Binary Search in Java

Coding:


import java.util.Scanner;



public class BinarySearch {

public static void main(String[] args) {

int[] a={1,2,3,4,5,6,7,8};

System.out.println("Enter element to search");

int x=(new Scanner(System.in)).nextInt();
int l=0,r=a.length-1;

while(true)
{

int mid=(l+r)/2;
System.out.printf("l=%s, mid= %s, r=%s\n",l,mid,r);

if(x==a[mid])

{

System.out.printf("Found at %s\n",mid);
return;

}

if(x>a[mid])
l=mid+1;
else
r=mid-1;

if(l>r)

{

System.out.printf("l=%s, mid= %s, r=%s\n",l,mid,r);
System.out.println("Not found");
return;

}
}

}
}

Output:

You have to Input a number by the keyboard to search it, to find whether the following number exists or not. For example, I have input Number 7, which is found at 6.

 

Leave a Reply