Program for Binary Search in Java

Program for binary search in java. In the Java programming language, a binary search is performed. This software is a step up from  the beginner’s java program. In Java, a binary search program can look for an element in an  array and print the value.

public class Main
{ 
public static void binarySearch(int arr[], int a, int b, int key)
{ 
int mid = (a + b)/2; 
while( a <= b ){ 
if ( arr[mid] < key ){ 
a = mid + 1; 
}else if ( arr[mid] == key ){ 
System.out.println("number is here " + mid); 
break; 
}else{ 
b = mid - 1; 
} 
mid = (a + b)/2; 
} 
if ( a > b ){ 
System.out.println("number not here"); 
} 
} 
public static void main(String args[]){ 
int arr[] = {10,20,30,40,50}; 
int key = 30; 
int b=arr.length-1; 
binarySearch(arr,0,b,key); 
} 
} 

 

Output:

number is here 2

Binary Search Algorithm in Java

Binary search is used to find a crucial element among a large number of other elements. The binary search method is faster than the linear search method. The array members must be in ascending order when using binary search. If you have an unsorted array, you can use Arrays to sort it. 

In Java, binary search is the most commonly used search method. The data must be sorted in ascending order before a binary search can be done. An iterative or recursive strategy can be used to implement a binary search.

While Loop to Execute Program for Binary Search in Java

The while loop in Java is a control flow statement that allows code to be repeated based on a Boolean condition. The while loop is similar to a looping if statement. A “While” Loop is used to repeat a block of code an unknown number of times until it meets a condition. 

The condition is assessed first in a while loop, and if it returns true, the statements inside the loop are executed. When the condition returns false, the control exits the while loop and moves on to the next line.

If Else Statement in Java

In Java, nested if statement refers to a “if statement” that is defined inside another if or if-else statement. Another if statement can be placed inside the inner if statement. In fact, the depth of the nesting has no limit. Yes, we may stack if statements within if statements in Java. An if statement can be nestled inside another if statement.  A user can choose from a variety of alternatives here.