Binary Search Program Java

Today, we will delve into binary search program java which uses Scanner class in java.util package. Here is example for binary search in java,

Example: Binary Search Program Java

Also Read – Calculate Average of an Array in Java

import java.util.Scanner;

public class Binary_Search {

public static void main(String[] args) {

int x;
int first, last, middle;
int y;
int search;
int[] array;

Scanner sc = new Scanner(System.in);
System.out.println("Please enter number of elements: ");
y = sc.nextInt();
array = new int[y];

System.out.println("Please enter " + y + " numbers: ");

for(x = 0;x < y;x++)
array[x] = sc.nextInt();

System.out.println("Please enter value to search: ");
search = sc.nextInt();

first = 0;
last = y - 1;
middle = (first/last) / 2;

while(first <= last){
if(array[middle] < search)
first = middle + 1;
else if(array[middle] == search){
System.out.println("The number " + search + " is at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;
middle = (first + last) / 2;
}
if(first > last)
System.out.println("The number " + search + " is not present in the list.");
}
}

Output:

Binary Search Program Java

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *